[英]Why is this dictionary comprehension for list of dictionaries not returning values?
[英]list comprehension returning 3 values
我想進行列表理解,因為使用for循環會使程序變慢,因此我希望將其轉換為列表理解。 但是,我希望它返回3個值,主要是i,ii和word。 我嘗試了我的方法,但收到如下錯誤:
錯誤:
ValueError: not enough values to unpack (expected 3, got 0)
關於我的代碼類型的簡介:
words: Is a list[List[string]] # [["I","have","something","to","buy"]]
word: is a word in string type
碼:
i, ii, word = [[i, ii, word] for i, w in enumerate(words) for ii, ww in
enumerate(w) for wwd in ww if word == wwd]
預期產量:
例如,i list將包含單詞的索引,ii list將包含w的索引,而word只是類似於wwd的字符串列表。
i = [0,1,2,3,4,5,6,7,8,9,10 ~] # this index should be relevant to the matching of wwd == word
ii = [0,1,2,3,4,5,6,7,8,9,10 ~] # this index should be relevant to the matching of wwd == word
word = ["I", "have", "something"] # this is received when comparing the wwd with word
#Another example: i= 2, ii= 4, word = "have" and then store it to the variables for each matching of word.
我想知道是否有更短的版本,如何解決當前問題?
我的問題的完整版本:
我的代碼:
wordy = [['I', 'have', 'something', 'to', 'buy', 'from', 'home', ',']]
key = {'I': 'We', 'king': 'man', 'value': 'time'}
a = []
def foo(a,b,c): return a,b,c
for ll in key.keys():
for ii, l in enumerate(wordy):
for i, word in enumerate(l):
for wordd in word:
if ll == wordd:
a.append(list(zip([ii, i, ll])))
for x in a:
i, ii, ll = foo(*x)
print(i,ii,ll)
for ll in key.keys():
a = [[i, ii, ll]for i, words in enumerate(wordy) for ii, word in enumerate(words) for wordd in word if ll == wordd]
print(a)
for x in a:
i, ii, ll = foo(*x)
print(i, ii, ll)
我當前的輸出:
0 0 I
[]
0 0 value
預期產量:
0 0 I
[]
0 0 I
我不知道為什么當使用列表推導時,“ ll”的值會變得不同。
您可以將zip
與*
運算符配合使用來解壓縮序列:
i, ii, word = zip(*([a, b, c] for ...))
假設您可以使用有意義的內容來填充...
請特別注意,不需要中介列表構造。 您可以使用生成器表達式,用括號代替方括號。
從技術上講,您的結果將是元組而不是列表。 對於列表,可以使用map
:
i, ii, word = map(list(zip(*...)))
我認為這是您想要做的:
wordlist = [['I', 'have', 'something', 'to', 'buy', 'from', 'home', ','],['You', 'king', 'thing', 'and', 'take', 'to', 'work', ',']]
dictionary = {'I': 'We', 'king': 'man', 'value': 'time'}
forloopoutput = []
listcompoutput = []
#For Loop
for key in dictionary.keys():
for wlist_index, wlist in enumerate(wordlist):
for word_index, word in enumerate(wlist):
if key == word:
forloopoutput.append([wlist_index, word_index, word])
#List comprehension
listcompoutput = [[wlist_index, word_index, word] for word_index, word in enumerate(wlist) for wlist_index, wlist in enumerate(wordlist)for key in dictionary.keys() if key==word]
為了清楚起見,我更改了一些內容:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.