如何迭代直到最长的迭代用尽。使用zip_longest进行迭代

时间:2019-02-16 04:39:41

标签: python list dictionary

我正在尝试使用itertools.zip_longest进行迭代,直到用尽最长的可迭代次数(而不是像常规zip那样最短的迭代次数)为止。我还需要将其传递给字典。但是,我仍然缺少价值。我应该有大约1300个值,但只能得到560个值。我缺少什么或做错了什么?

import csv
from itertools import zip_longest

my_csv = 'my_csv_file' + '.csv'

some_list = []
another_list = []
my_dictionary = {}

with open(my_csv, newline='') as f:
    reader = csv.reader(f)
    next(reader, None)
    for row in reader:
        some_list.append(row[0])
        another_list.append(row[1:])

my_dictionary = dict(zip_longest(some_list, another_list, fillvalue=None))

for v in my_dictionary.keys():
    print(v)

count = len(my_dictionary.keys())
print(str(count) + " keys")

2 个答案:

答案 0 :(得分:1)

听起来有些键具有重复的值,它们将折叠为最新值(例如:{1: 'a', 2: 'b', 1: 'c'}将折叠为{1: 'c', 2: 'b'})。

您可能想使用list作为值:

from collections import defaultdict

# Set-up...

my_dictionary = defaultdict(list)
for key, value in zip_longest(some_list, another_list, fillvalue=None)
    my_dictionary[key].append(value)

for v in my_dictionary.keys():
    print(v)

keys = len(my_dictionary)
values = sum(len(value) for value in my_dictionary.itervalues())
print(str(keys) + " keys, " + str(values) +  " values")

答案 1 :(得分:0)

对我来说,您要输出的内容还不是很清楚,但是也许其中一个示例可以提供帮助。

给出以下csv文件内容:

a,b,c
11,12,13
21,22,23


第一个选项是将标头放置在列表中,然后将其余数据放入另一个列表中。然后在压缩列表中调用dict(),无需在此处使用zip_longest

with open(my_csv, newline='') as f:
    reader = csv.reader(f)
    headers = next(reader, None) # place headers in a list
    rows = [row for row in zip(*reader)] # this transpose the data

print(rows) #=> [('11', '21'), ('12', '22'), ('13', '23')]

my_dictionary = dict(zip(headers, rows))
print(my_dictionary)
#=> {'a': ('11', '21'), 'b': ('12', '22'), 'c': ('13', '23')}


第二个选项构建词典列表:

my_dictionaries = []
with open(my_csv, newline='') as f:
    reader = csv.reader(f)
    headers = next(reader, None) # place headers in a list
    for row in reader:
      my_dictionaries.append(dict(zip(headers, row)))

print(my_dictionaries)
#=> [{'a': '11', 'b': '12', 'c': '13'}, {'a': '21', 'b': '22', 'c': '23'}]