python - 列表理解返回 3 个值
问题描述
我想做一个列表推导,因为使用 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”的值会变得不同。
解决方案
我认为这就是你想要做的:
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]
为了清楚起见,我更改了一些内容:
- 我给变量起更清晰(但更长)的名称以便于解释。
- 我假设您的“冗长”列表是一个嵌套列表,因为在您的现实生活示例中,您期望有多个列表,因此我在示例中添加了另一个列表以演示它的用途。
推荐阅读
- excel - 如何将XML中的数组值插入Excel中行的每个顺序单元格,为每一行循环?
- python - Python没有这样的文件或目录错误尝试在Mac上打印文件列表目录
- c++ - 我试图制作一个要求用户输入问题和答案的程序,但程序没有正确循环
- firebase - 使用 Flutter Firestore Firebase 将值保存为字符串
- mysql - 您如何根据 MIN 日期对值求和?
- javascript - 尝试对 firebase 数据库进行排序不起作用
- angular - Angular 5 使用 @ViewChildren 访问 div 列表
- java - 改造返回对象参数乱序,带有@符号和引号
- java - 如何在流 API 中使用返回范围?
- dapper - MySQL + Dapper 扩展:SQL 语法错误