我有两个列表:
l1 = ['a','b','c','d','e','f','g','h', ...]
l2 = ['dict1','dict2','dict3','dict4','dict5','dict6','dict7','dict8', ...]
我需要一次对每个列表 50 个项目的块运行一个函数,并且在函数返回每个列表中前 50 个项目的结果之前,它无法继续。
我的第一个想法是使用生成器:
def list1_split(l1):
n = 50
for i in range(0, len(l1), n):
yield l1[i:i+n]
def list2_split(l2):
n = 50
for i in range(0, len(l2), n):
yield l2[i:i+n]
chunk_l1 = list1_split(l1)
chunk_l2 = list1_split(l1)
然后,当使用这两个列表时,我将它们放在主函数中:
def query(chunk_l1, chunk_l2):
count = 0
query_return_dict = {}
for i, j in zip(chunk_l2, chunk_l1):
count += 1
query_return_dict[i] = j
print('This is number ', count, 'n', j)
return query_return_dict
def main():
thread = threading.Thread(target=query(chunk_l1, chunk_l2))
thread.start()
print('Done!')
if __name__ == '__main__':
main()
我得到的第一个错误与生成器无关(我认为(:
TypeError: 'dict' object is not callable
但真正让我失望的是,当我使用调试器时,我的 for 循环将每个列表解释为:
i: <class 'list'>: ['a','b','c','d','e',...]
j: <class 'list'>: ['dict1','dict2','dict3','dict4',...]
而不是i: 'a', j: 'dict1'
,最重要的是,我得到一个错误说,
TypeError: unhashable type: 'list'
我对生成器不太熟悉,但它似乎对于一次运行一个块的函数最有用
首先,i
和 j
并不像您想象的那样是字符串,但它们本身就是列表。
当您执行query_return_dict[i]
时,您会TypeError: unhashable type: 'list'
错误,因为您尝试将列表用作字典键,但您无法这样做,因为列表是可变的,因此不可散列,并且字典键应始终是可哈希的
要从列表中提取字符串,您需要另一个 for 循环,它遍历i
和j
并创建您的query_return_dict
def query(chunk_l1, chunk_l2):
query_return_dict = {}
#i and j are chunks
for i, j in zip(chunk_l1, chunk_l2):
#Zip chunks together to extract individual elements
for key, value in zip(i, j):
#Create your dictionary
query_return_dict[key] = value
另外thread = threading.Thread(target=query(chunk_l1, chunk_l2))
不是如何将函数作为目标传递给线程,而是您想要这样做
thread = threading.Thread(target=query, args=(chunk_l1, chunk_l2))
从文档中: https://docs.python.org/3/library/threading.html#threading.Thread
目标是要由 run(( 方法调用的可调用对象。默认为 None,表示不调用任何内容。
args 是目标调用的参数元组。默认值为 ((。