简体   繁体   中英

Returning a certain list structure in Python

我在使用列表(和列表列表,以及lt ...的列表列表)结构时遇到麻烦。

Use t the += instead of the .append() operator. and use a second list temp

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

edit:

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

is better as it saves you from making temp

endEdit

The behavioural difference here is as follows.

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

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

Vs.

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

[ 1 , 2 , 3 , 4 , 5 ]

You need to add a new list in your loop and collapse the 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

You could also do this with a list comprehension:

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

Output:

>>> convert_to_phonemes([['THE', 'FIRST'], ['WITH', 'A']], key_to_phonemes)
[['DH', 'AH0', 'F', 'ER1', 'S', 'T'], ['W', 'IH1', 'DH', 'AH0']]
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

As for each sublist you are creating a new list.And then using set concept we are adding distinct key_to_phonemes to the last element of the list.

You can done this using 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']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM