[英]How to iterate over a list of lists and print items of each list as a comma-delimited string
If I have a list of lists:如果我有一个列表列表:
x = [['1','2','3'],['4','5','6'],['7','8','9']]
How do I iterate over these lists and print them to get the following output?我如何遍历这些列表并打印它们以获得以下输出?
1, 2, 3
4, 5, 6
7, 8, 9
Try this:试试这个:
for l in x:
print ', '.join(map(str, l))
Output:输出:
1, 2, 3 4, 5, 6 7, 8, 9
You pretty much have it:你几乎拥有它:
# python
x = [['1','2','3'],['4','5','6'],['7','8','9']]
for i in x:
print i[0]
1
4
7
for i in x:
print i
['1', '2', '3']
['4', '5', '6']
['7', '8', '9']
for i in x[0]:
print i
1
2
3
You can use itertools.chain
:您可以使用
itertools.chain
:
from itertools import chain
for i in chain.from_iterable(x):
print i
If you're talking about processing each element in the arrays one-by-one (I'm assuming here that the printing is just an example and your your actual desired processing is more complicated), the simplest way is to not do that.如果您正在谈论逐个处理数组中的每个元素(我在这里假设打印只是一个示例,您实际需要的处理更复杂),最简单的方法是不这样做。 You obviously have your data structured in that way for a reason, in which case your code should mirror it.
您显然出于某种原因以这种方式构建了数据,在这种情况下,您的代码应该反映它。
You save very little by doing that with a single for
statement so I would use:使用单个
for
语句可以节省很少的钱,所以我会使用:
for xlist in x:
for n in xlist:
do something with n
Believe it or not, having your code mirror your data actually improves code readability.信不信由你,让你的代码反映你的数据实际上提高了代码的可读性。
As an example, to get your exact output as specified in the edit:例如,要获得编辑中指定的准确输出:
#!/usr/bin/python
x = [['1','2','3'],['4','5','6'],['7','8','9']]
for xlist in x:
s = ""
for n in xlist:
s = "%s, %c"%(s,n)
print s[2:]
Just for the concept, the actual traversal is very simple:只是为了概念,实际遍历很简单:
for i in x: #a list
for j in i: #elements of the list
print j
This will print 1 2 3 4 5 6 7 8 9, every number in a newline这将打印 1 2 3 4 5 6 7 8 9,每个数字换行
You can change the pattern as you would want.您可以根据需要更改模式。
x = [['1','2','3'],['4','5','6'],['7','8','9']]
[k for y in x for k in y]
Output:输出:
['1', '2', '3', '4', '5', '6', '7', '8', '9']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.