我有这个清单:

list1 = ["happy","sad","love","bad"]

我想复制每个单词的最后一个字符,应该是这样的:
list2 = ["happyy","sadd","lovee","badd"]

我试过这个:
list1 = ["happy","sad","love","bad"]
l = len(list1)-1
ls = len(list1[l])-1
list2 = []
k=0
i=0
for k in list1[l]:
   for i in list1[ls]:
       list2.append(list1[l]+list1[ls-1])
print(list2)

我明白了:
['badsad','badsad','badsad','badsad','badsad','badsad','badsad','badsad','badsad','badsad','badsad','badsad','badsad']

最佳答案

使用列表理解。s[-1]将给您字符串的最后一个字符。所以您应该确保不要索引到空字符串中。

>>> list1 = ["happy","sad","love","bad",'']
>>> [s + s[-1] if s else s for s in list1]
['happyy', 'sadd', 'lovee', 'badd', '']

备选方案:
>>> [s + s[len(s)-1:] for s in list1]
['happyy', 'sadd', 'lovee', 'badd', '']

我觉得第二个比较好看。
编辑:事实上,我更喜欢这个,我不知道它是怎么躲过我的:
>>> list1 = ["happy","sad","love","bad",'']
>>> [s + s[-1:] for s in list1]
['happyy', 'sadd', 'lovee', 'badd', '']

关于python - 使用python将每个字符串列表的最后一个字符加倍,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36589674/

10-09 17:11