如何迭代直到最长的迭代用尽.使用zip_longest进行迭代 [英] How to iterate until longest iterable is exhausted. Using zip_longest to iterate
问题描述
我正在尝试使用 itertools.zip_longest 继续进行迭代,直到用尽最长的可迭代项(而不是像常规zip那样最短).我还需要将其传递给字典.但是,我仍然缺少价值观.我应该有大约1,300个值,但只能得到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")
听起来好像有重复值的键,它们将折叠为最新值(例如:{1: 'a', 2: 'b', 1: 'c'}
将折叠为{1: 'c', 2: 'b'}
). /p>
您可能想使用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")
I'm trying to use itertools.zip_longest to continue to iterate until the longest iterable is exhausted (instead of the shortest as regular zip does). I also need to pass this into a dictionary. However, I'm still missing values. I should have about 1,300 values but only getting about 560. What am I missing or doing wrong?
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")
It sounds like there are keys with duplicate values, which will collapse to the most recent value (e.g.: {1: 'a', 2: 'b', 1: 'c'}
would collapse to {1: 'c', 2: 'b'}
).
You might want to use list
as values instead:
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")
这篇关于如何迭代直到最长的迭代用尽.使用zip_longest进行迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!