gpt4 book ai didi

python - 有没有办法将列表中的索引组合起来

转载 作者:太空宇宙 更新时间:2023-11-03 15:17:22 26 4
gpt4 key购买 nike

我不知道这是否可行,到目前为止我还没有找到办法。我有一个包含名称的列表列表。某些列表有 2 个元素,其他列表有 3 个 [['Doe', 'John'], ['Doe', 'Jr.,', 'John']]。有没有办法将索引组合到列表列表中。我可以使用单个列表来完成此操作,但当我在列表列表上尝试时,出现错误:TypeError:equence item 0:expected str instance, listfound。我试图做这样的事情:

while(len(name_list) > 2:
indices = [0, 1]
name_list = ['Doe', 'Jr.,', 'John']

join_index = ' '.join([e for i, e in enumerate(name_list) if i in indices])
print(join_index)

最佳答案

看来您正在尝试组合名称以从更复杂的内容中生成(最后一个、第一个)。

此代码将组合子列表中除最后一个元素之外的所有元素:

代码:

names = [['Doe', 'John'], ['Doe', 'Jr.,', 'John']]
print(names)

new_list = [[' '.join(n[:-1]), n[-1]] for n in names]
print(new_list)

结果:

[['Doe', 'John'], ['Doe', 'Jr.,', 'John']]

[['Doe', 'John'], ['Doe Jr.,', 'John']]

关于python - 有没有办法将列表中的索引组合起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43774214/

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