列表理解返回3个值

时间:2018-10-10 01:25:38

标签: python list list-comprehension

我想进行列表理解,因为使用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”的值变得不同。

2 个答案:

答案 0 :(得分:1)

您可以将zip*运算符配合使用来解压缩序列:

i, ii, word = zip(*([a, b, c] for ...))

这假设您可以用有意义的内容填充...。请特别注意,不需要中介列表构造。您可以使用生成器表达式,用括号代替方括号。

从技术上讲,您的结果将是元组而不是列表。对于列表,您可以使用map

i, ii, word = map(list(zip(*...)))

答案 1 :(得分:1)

我认为这是您想要做的:

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]

为了清楚起见,我更改了一些内容:

  • 我为变量指定了更清晰(但更长)的名称,以便于解释。
  • 我假设您的“罗y”列表是嵌套列表,因为在您的实际示例中,您期望有多个列表,因此我在示例中添加了另一个列表以演示其用法。