![](/img/trans.png)
[英]python: flatten list while preserving nested structure for certain indexes
[英]Returning a certain list structure in Python
我在使用列表(和列表列表,以及lt ...的列表列表)結構時遇到麻煩。
使用+ =代替.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 ] ]
比。
[1,2,3] + [4,5]
[ 1 , 2 , 3 , 4 , 5 ]
您需要在循環中添加新列表並折疊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']]
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
對於每個子列表,您都將創建一個新列表。然后使用集合概念,我們將不同的key_to_phonemes添加到列表的最后一個元素。
您可以使用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']]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.