简体   繁体   English

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

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

I have a long list with tokens like this: 我有一长串这样的令牌:

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

I would like to separate each token or term with a comma like this (*): 我想用这样的逗号(*)分隔每个标记或术语:

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

I tried to: 我试过了:

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

However, is not working. 但是,不起作用。 Amy idea of how to get (*)? 艾米关于如何获得(*)的想法?

If a_lis is 如果a_lis

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

then we can flatten that to a list of strings, and split each of those strings 然后我们可以将其展平为字符串列表,并split每个字符串

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

gives us 给我们

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

Another way of doing it with map 使用地图的另一种方法

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)

Basically, use the .split() method for a string with a space as an argument. 基本上,对带有空格作为参数的字符串使用.split()方法。 Also, make sure you put quotation marks around those strings! 另外,请确保在这些字符串周围加上引号!

If you have a list of lists, just add another for loop: 如果您有一个列表列表,只需添加另一个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)

Here's a functional approach: 这是一种实用的方法:

>>> 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