gpt4 book ai didi

python - 使用条件在循环中加入字符串列表中的元素

转载 作者:行者123 更新时间:2023-12-04 02:28:35 24 4
gpt4 key购买 nike

每2个元素应该加入一个循环直到列表的末尾这就是我一直在努力做的事情

items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
for i in range(len(items)+1):
items[i]=items[i]+items[i+1]
i=i+2
print(items)

预期输出:['ab'、'cd'、'ef'、'gh'、'ij']

最佳答案

您可以为 range 提供另一个参数指定增量(“step”):

items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
res = []
for i in range(0, len(items), 2):
res.append(items[i] + items[i + 1])
print(res)
# ['ab', 'cd', 'ef', 'gh', 'ij']

或者,更好的是,使用 list comprehension相反:

items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
items = [items[i] + items[i + 1] for i in range(0, len(items), 2)]
print(items)
# ['ab', 'cd', 'ef', 'gh', 'ij']

关于python - 使用条件在循环中加入字符串列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65701617/

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