簡體   English   中英

如何用逗號分隔嵌套列表的所有元素?

[英]How to separate by comma all the elements of a nested list?

我有一長串這樣的令牌:

 a_lis = [['hi how are you'],
['im fine thanks'],
['cool lets go to the restaurant']
,...,
['I can't now']]

我想用這樣的逗號(*)分隔每個標記或術語:

 a_lis = [['hi', 'how', 'are', 'you'],
['im', 'fine', 'thanks'],
['cool', 'lets', 'go', 'to', 'the', 'restaurant']
,...,
['I', 'can't', 'now']]

我試過了:

[x.replace(' ', ', ') for x in a_lis]

但是,不起作用。 艾米關於如何獲得(*)的想法?

如果a_lis

a_lis = [["hi how are you"],
["im fine thanks"],
["cool lets go to the restaurant"],
["I can't now"]]

然后我們可以將其展平為字符串列表,並split每個字符串

[s.split() for l in a_lis for s in l]

給我們

[['hi', 'how', 'are', 'you'], ['im', 'fine', 'thanks'], ['cool', 'lets', 'go', 'to', 'the', 'restaurant'], ['I', "can't", 'now']]

使用地圖的另一種方法

a_lis = [["hi how are you"],["good and you"]]
new_list = list(map(lambda x: x[0].split(' '), a_lis))
# new_list is [['hi', 'how', 'are', 'you'], ['good', 'and', 'you']]
a_list = ['hmm this is a thing', 'and another']
new_list = []
for i in a_list:
    new_list.append(i.split(' '))
print(new_list)

基本上,對帶有空格作為參數的字符串使用.split()方法。 另外,請確保在這些字符串周圍加上引號!

如果您有一個列表列表,只需添加另一個for循環即可:

a_list = [['hmm, this is a thing', 'and another'], ['more things!']]
new_list = []
for i in a_list:
    sub_list = []
    for k in i:
        sub_list.append(k.split(' '))
    new_list.append(sub_list)

這是一種實用的方法:

>>> from operator import itemgetter
>>> a_lis = [["hi how are you"],["good and you"]]
>>> list(map(str.split, map(itemgetter(0), a_lis)))
[['hi', 'how', 'are', 'you'], ['good', 'and', 'you']]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM