gpt4 book ai didi

python - 合并字符串列表和列表列表

转载 作者:行者123 更新时间:2023-11-28 19:17:15 25 4
gpt4 key购买 nike

这可能是重复的,但我找不到具体的答案。

我在撰写这个问题时也找到了一个答案,但想知道是否有更好的选择,或者在不知道哪一项是字符串列表的情况下可以工作的选择。

我的问题:

la=['a', 'b', 'c']
lb=[['d','e'], ['f','g'], ['i','j']]

我愿意:

[['a','d','e'], ['b','f','g'], ['c','i','j']]

我发现了以下专门针对我的示例的作品;

la=['a', 'b', 'c']
lb=[['d','e'], ['f','g'], ['i','j']]
[ [x] + y for x,y in zip(la, lb)]
[['a', 'd', 'e'], ['b', 'f', 'g'], ['c', 'i', 'j']]

之所以有效,是因为我在连接之前将字符串列表变成了列表,并避免了TypeError: cannot concatenate 'str' and 'list' objects

有没有更优雅的解决方案?

最佳答案

你可以使用numpy.column_stack:

>>> la=['a', 'b', 'c']
>>> lb=[['d','e'], ['f','g'], ['i','j']]
>>> import numpy as np

>>> np.column_stack((la,lb))
array([['a', 'd', 'e'],
['b', 'f', 'g'],
['c', 'i', 'j']],
dtype='|S1')

关于python - 合并字符串列表和列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32118122/

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