gpt4 book ai didi

python - 如何在单行中使用 for 循环将这些列表拆分为列表?

转载 作者:太空宇宙 更新时间:2023-11-04 00:10:19 38 4
gpt4 key购买 nike

我想把 pandas 中的 list flatten([[list1], [list2], [list3] ....])

有人能告诉我如何在单行中制作“for 循环”吗?谢谢(还有其他办法解决吗?)

words = []
for sent in train['tokenize']:
words += sent

我想要的结果是 [[list1], [list2], [list3]] >> [list1, list2, list3]

最佳答案

使用列表理解:

words = [a for sub in train['tokenize'] for a in sub]

chain.from_iterable :

from  itertools import chain
words = list(chain.from_iterable(train['tokenize']))

示例:

train = pd.DataFrame({'tokenize':[['a','s','d'],['ss','dd'],['aa','ss','dd']]})
print (train)
tokenize
0 [a, s, d]
1 [ss, dd]
2 [aa, ss, dd]

words = [a for sub in train['tokenize'] for a in sub]
print (words)
['a', 's', 'd', 'ss', 'dd', 'aa', 'ss', 'dd']

关于python - 如何在单行中使用 for 循环将这些列表拆分为列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52713780/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com