Python 如何迭代奇数索引并将其添加回原始列表
我想在列表中的每一个单数索引(或每一个单词)后添加“…”,但我不太明白该怎么做。我建议这样做。起初我不理解你的问题Python 如何迭代奇数索引并将其添加回原始列表,python,python-3.x,list,Python,Python 3.x,List,我想在列表中的每一个单数索引(或每一个单词)后添加“…”,但我不太明白该怎么做。我建议这样做。起初我不理解你的问题 blah = input().split() res = "".join( word + "..." if i % 2 == 0 else word for i, word in enumerate(blah) ) print(res) 您可以使用类似的方法: sentence = input().split() an
blah = input().split()
res = "".join(
word + "..." if i % 2 == 0 else word
for i, word in enumerate(blah)
)
print(res)
您可以使用类似的方法:
sentence = input().split()
ans = []
for i in range(len(sentence)):
if i%2:
ans.append(sentence[i]+'...')
else:
ans.append(sentence[i])
print(' '.join(ans))
>>> def newList(lst):
for i in range(len(lst)):
if i%2 != 0:
lst[i] = str(lst[i]) + "..."
return lst
>>> l = ['a','b','c','d','e','f']
>>> print(newList(l))
output:
['a', 'b...', 'c', 'd...', 'e', 'f...']