我有2个包含6个元素的列表和一个将行写入csv文件的循环。例如:
list1 = [1, 2, 3, 4, 5, 6]
list2 = [a, b, c, d, e, f]
for i in range(0, 6):
writer.writerow([stuff1, stuff2, list_element1, list_element2])
我想选择列表1和2的第一个元素并将它们添加到行的末尾,之后我想选择列表1和2的第二个元素并将它们添加到我的csv文件的第二行[...]。
提前致谢。
答案 0 :(得分:2)
有多种方式,都取决于您迭代的对象类型和运行时考虑因素。对于这个简单的例子,任何事都应该没问题,但要考虑各自的优点和缺点。
list1 = [1, 2, 3, 4, 5, 6]
list2 = [a, b, c, d, e, f]
# way 1
for l1, l2 in zip(l1, l2):
writer.writerow([stuff1, stuff2, l1, l2])
from itertools import izip, izip_longest
# way 2: for equal lengths, better if iterable don't support __len__
# for e.g. generators not having len
for i, _ in enumerate(list1):
print i
writer.writerow([stuff1, stuff2, list1[i], list2[i])
# way 3: for equal lengths
# using len() would break if iterable don't support it.
for i in range(len(list1)):
writer.writerow([stuff1, stuff2, list1[i], list2[i]])
# way 4: for equal lengths - better for huge lists
for i in xrange(len(list1)):
writer.writerow([stuff1, stuff2, list1[i], list2[i]])
# way 5: izip - equal lengths
list1 = [1, 2, 3, 4, 5, 6]
list2 = [7, 8, 9 ,10, 11, 12]
for l1, l2 in izip(list1, list2):
writer.writerow([stuff1, stuff2, l1, l2])
# way 6: for different lengths
list1 = [1, 2, 3, 4, 5, 6]
list2 = [7, 8, 9 ,10, 11, 12, 13]
for l1, l2 in izip_longest(list1, list2):
writer.writerow([stuff1, stuff2, l1, l2])
# way 7: for different lengths
for l1, l2 in map(None, list1, list2):
writer.writerow([stuff1, stuff2, l1, l2])
答案 1 :(得分:0)
假设list1和list2具有相同的长度,使用zip(list1,list2)可能看似pythonic但是它增加了空间复杂性并且生成元组的额外时间因为zip
不会创建生成器而不是元组。因此,虽然以下内容obvious
并且简单,但它也是最优的
list1 = [1, 2, 3, 4, 5, 6]
list2 = [a, b, c, d, e, f]
for i in xrange(len(list1)):
writer.writerow([stuff1, stuff2, list1[i], list2[i])