在Python中返回某个列表结构

时间:2015-04-01 04:47:08

标签: python

我在列表(以及列表列表和lt ...列表)结构方面遇到了问题。

4 个答案:

答案 0 :(得分:1)

使用+ =而不是.append()运算符。 并使用第二个列表临时

new_list = []
for sublist in lines:
    temp = []
    for word in sublist:
        temp+=key_to_phonemes[word]
    new_list.append(temp)

编辑:

new_list = []
for n,sublist in enumerate(lines):
    new_list.append([])
    for word in sublist:
        new_list[n]+=key_to_phonemes[word]

更好,因为它可以让你免于犯罪

EndEdit中

这里的行为差异如下。

  

[1,2,3] .append([4,5])

[ 1 , 2 , 3 , [ 4 , 5 ] ]

Vs以上。

  

[1,2,3] + [4,5]

[ 1 , 2 , 3 , 4 , 5 ]

答案 1 :(得分:0)

您需要在循环中添加新列表并折叠key_to_phonemes:

new_list = []

for sublist in lines:
    sub = []
    for word in sublist:
        for phoneme in key_to_phonemes[word]:
            sub.append(phoneme)
    new_list.append(sub)
return new_list

你也可以用列表理解来做到这一点:

return [[p for word in sublist for p in key_to_phonemes[word]] for sublist in lines]

输出:

>>> convert_to_phonemes([['THE', 'FIRST'], ['WITH', 'A']], key_to_phonemes)
[['DH', 'AH0', 'F', 'ER1', 'S', 'T'], ['W', 'IH1', 'DH', 'AH0']]

答案 2 :(得分:0)

for sublist in lines:
    new_list.append([])
    for word in sublist:
        x = set(key_to_phonemes[word])
        y = set(new_list[-1])
        y = list(x.union(y))
        new_list[-1] = y
return new_list

对于每个子列表,您要创建一个新列表。然后使用set concept,我们将不同的key_to_phonemes添加到列表的最后一个元素。

答案 3 :(得分:0)

您可以使用list comprehension

完成此操作
lines = [['THE', 'FIRST'], ['WITH', 'A']]
key_to_phonemes = {'WITH': ['W', 'IH1', 'DH'], 'THE': ['DH', 'AH0'], 'A': ['AH0'], 'FIRST': ['F', 'ER1', 'S', 'T']}

def convert_to_phonemes(lines, word_to_phonemes):
    return [[k for j in i for k in key_to_phonemes[j]] for i in lines]

>>>convert_to_phonemes(lines, word_to_phonemes)
[['DH', 'AH0', 'F', 'ER1', 'S', 'T'], ['W', 'IH1', 'DH', 'AH0']]