Python 如何迭代直到最长的iterable耗尽。使用zip_进行迭代

Python 如何迭代直到最长的iterable耗尽。使用zip_进行迭代,python,list,dictionary,Python,List,Dictionary,我试图使用继续迭代,直到最长的iterable被耗尽,而不是像常规zip那样的最短iterable。我还需要把这个输入字典。但是,我仍然缺少值。我应该有大约1300个值,但只有大约560个。我错过了什么或做错了什么 import csv from itertools import zip_longest my_csv = 'my_csv_file' + '.csv' some_list = [] another_list = [] my_dictionary = {} with open(

我试图使用继续迭代,直到最长的iterable被耗尽,而不是像常规zip那样的最短iterable。我还需要把这个输入字典。但是,我仍然缺少值。我应该有大约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")

听起来好像有些键具有重复的值,它们将折叠到最近的值,例如:{1:'a',2:'b',1:'c'}将折叠到{1:'c',2:'b'}

您可能希望改用列表作为值:

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")

我还不完全清楚您想要输出什么,但是这些示例中的一个可能会有所帮助

给定此csv文件内容:

a,b,c
11,12,13
21,22,23
第一种选择是在列表中放置标题,然后在另一个列表中传输其余数据。然后在压缩列表中调用dict,此处无需压缩:

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

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'}]

听起来好像有两个重复值的键,它们会坍塌到最新的值,例如:{ 1:‘A’,2:‘B’,1:‘C’}会塌缩到{ 1:‘C’,2:‘B’}。或者你使用小列表作为一个键,导致多个Na作为键,但是DICT只考虑一个。为什么你认为ZIPLUBULY会产生影响?您将相同数量的元素添加到两个列表中。请提供一个示例输入文件来显示您的问题。把文件剪成十几行或更少的行,这样你就可以把它贴在这里了。谢谢大家的帮助!因此,我的CSV包含URL。第一列有新的URL。其余的都是旧的URL。我想看看[1:]上的第2列和第2列,如果在一组HTM文件中找到了这些URL中的任何一个,请将其替换为新的URL第1列。我遇到了一个问题,当时没有找到所有的URL,我跟踪到zipdict没有完全迭代,因为有一些列是不均匀的。我在CSV中填写了空格,但仍然无法打印超过560行。只是花了一天的时间尝试提出的建议,但毫无效果。这里有一个指向示例CSV的链接。
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'}]