[英]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.