Python 如何打印元组列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15127197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to print a list of tuples
提问by yiwei
I have a list of tuples, called gradebook, where each list element is a tuple that corresponds to a class and a grade that a student can earn. For example,
我有一个名为 的元组列表gradebook,其中每个列表元素都是一个元组,对应于学生可以获得的班级和成绩。例如,
gradebook = [('Math 212', 'Linear Algebra', 'Fall 2012', 'B'),
('CS 130', 'Python', 'Spring 2013', 'A')]
And so on. I would like it to print like this:
等等。我希望它像这样打印:
Class: Math 212.....Subject: Linear Algebra.....Term: Fall 2012.....Grade: B`
Class: CS 130.......Subject: Computer Science...Term: Spring 2013...Grade: A`
I would like to be able to go through each tuple in the list, and then print out each element of the tuple. How can I achieve this?
我希望能够遍历列表中的每个元组,然后打印出元组的每个元素。我怎样才能做到这一点?
EDIT: This is what I have right now:
编辑:这就是我现在所拥有的:
for aTuple in gradebook:
print(aTuple)
Sorry, I'm very new to Python, so I don't really understand how this works.
抱歉,我对 Python 很陌生,所以我不太明白这是如何工作的。
采纳答案by eazar001
General format, you can iterate through a list and access the index of a tuple:
一般格式,你可以遍历一个列表并访问一个元组的索引:
for x in gradebook:
print x[0], x[1]
x[0] in this example will give you the first part of the tuple, and x[1] .... so on. Mess around and experiment with that format, and you should be able to do the rest on your own.
在这个例子中 x[0] 会给你元组的第一部分,和 x[1] .... 等等。乱七八糟地尝试这种格式,你应该能够自己完成剩下的工作。
EDIT: Although some of the other answers are nicer here, in the sense that they unpack the tuples and follow the "way of Python" more closely. Like such:
编辑:尽管其他一些答案在这里更好,但从某种意义上说,它们解压缩了元组并更紧密地遵循“Python 方式”。像这样:
a, b, c = ('a','b','c')
回答by jurgenreza
Use string formatting:
使用字符串格式:
for aTuple in gradebook:
print('Class: %s.....Subject: %s.....Term: %s.....Grade: %s' % aTuple)
回答by Tyler MacDonell
Or you could do this...
或者你可以这样做...
for id, name, semester, grade in gradebook:
print id, name, semester, grade
回答by wim
gradebook = [('Math 212', 'Linear Algebra', 'Fall 2012', 'B'), ('CS 130', 'Python', 'Spring 2013', 'A')]
fieldwidths = 13, 19, 14, 1
for tup in gradebook:
tup = (s.ljust(w, '.') for s,w in zip(tup, fieldwidths))
print 'Class: {}Subject: {}Term: {}Grade: {}'.format(*tup)
I have manually set the field widths to match your example. But you might prefer to generate fieldwidths in a smart way, i.e. based on column-maximums of element lengths in gradebook.
我已手动设置字段宽度以匹配您的示例。但是您可能更喜欢以智能方式生成字段宽度,即基于成绩簿中元素长度的列最大值。
Next time, a better data structure for your gradebook entries would be a dictinstead of a tuple.
下次,成绩簿条目的更好数据结构将是 adict而不是tuple.
回答by ds440
You can index by assigning elements names (sometimes convenient if you're calculating something):
您可以通过分配元素名称来索引(如果您正在计算某些内容,有时会很方便):
for (a, b, c, d) in gradebook:
print "Class: ", a, "...Subject: ", b, "...Term: ", c, "...Grade: ", d
Class: Math 212 ...Subject: Linear Algebra ...Term: Fall 2012 ...Grade: B
班级:数学 212 ...科目:线性代数 ...学期:2012 年秋季 ...年级:B
Class: CS 130 ...Subject: Python ...Term: Spring 2013 ...Grade: A
课程:CS 130 ...主题:Python ...学期:2013 年春季 ...等级:A
For more even spacing:
为了更均匀的间距:
for (a, b, c, d) in gradebook:
print "Class: ", a, "."*(20-len(a)), "Subject: ", b, "."*(20-len(b)), "Term: ", c, "."*(20-len(c)), "Grade: ", d
Class: Math 212 ............ Subject: Linear Algebra ...... Term: Fall 2012 ........... Grade: B
班级:数学 212 ...... 科目:线性代数 ...... 学期:2012 年秋季 ...... 成绩:B
Class: CS 130 .............. Subject: Python .............. Term: Spring 2013 ......... Grade: A
班级:CS 130 .....................科目:Python ......学期:2013 年春季......年级:一种
回答by Octipi
I'm not too familiar with some of the more advanced formatting options in python. That being said, this will display the results as requested. You can access the elements in each tuple by their index. '.'*(#-len('column info'+g[i]))gives the correct number of periods by subtracting the length of the string from the column width. To print this without spaces between elements you use the sep=''in print()
我对 python 中的一些更高级的格式化选项不太熟悉。话虽如此,这将按要求显示结果。您可以通过索引访问每个元组中的元素。 '.'*(#-len('column info'+g[i]))通过从列宽中减去字符串的长度,给出正确的句点数。要打印此元素之间没有空格,请使用sep=''inprint()
gradebook = [('Math 212', 'Linear Algebra', 'Fall 2012', 'B'), ('CS 130', 'Python', 'Spring 2013', 'A')]
for g in gradebook:
print('Class: ', g[0], '.'*(20-len('Class: '+g[0])),
'Subject: ', g[1], '.'*(28-len('Subject: '+g[1])),
'Term: ', g[2], '.'*(20-len('Term: '+g[2])),
'Grade: ', g[3], sep = '')
回答by Griffin_han
you can define a function naming __str__(self), which return a string like the form "Class: Math 212.....Subject: Linear Algebra.....Term: Fall 2012.....Grade: B" in the class .
then you can use your code:
您可以定义一个函数命名__str__(self),它在类中返回一个类似于“类:数学 212.....主题:线性代数.....术语:2012 年秋季.....等级:B”形式的字符串。然后你可以使用你的代码:
for aTuple in gradebook:
print(aTuple)
to get the expected output.
以获得预期的输出。
回答by eyquem
gradebook = [('Math 212', 'Linear Algebra', 'Fall 2012', 'B'),
('CS 130', 'Python', 'Spring 2013', 'A'),
('Economics History','1914','Fall 14','D')]
fields = '...'.join( '{:.<%ds}' % max(map(len,cat))
for cat in zip(*gradebook) )
print 'fields :\n%r\n\n' % fields
def disp(x,fields=fields):
if all(isinstance(el,tuple) for el in x):
# x is a collections of tuples
print '\n'.join(fields.format(*el) for el in x)
elif all(isinstance(el,str) for el in x):
# x is a collection of strings
print fields.format(*x)
print 'disp(gradebook) :\n\n',
disp(gradebook)
print '\n'
print 'disp(gradebook[1]) :\n\n',
disp(gradebook[1])
result
结果
fields :
'{:.<17s}...{:.<14s}...{:.<11s}...{:.<1s}'
disp(gradebook) :
Math 212............Linear Algebra...Fall 2012.....B
CS 130..............Python...........Spring 2013...A
Economics History...1914.............Fall 14.......D
disp(gradebook[1]) :
CS 130..............Python...........Spring 2013...A

