python - 使用python将每个字符串列表的最后一个字符加倍

标签 python list

我有这个列表:

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']

最佳答案

在 Python 中,您可以使用切片来执行此操作。

list1 = ["happy","sad","love","bad"]
list2 = []
for l in list1:
    list2.append(l+l[-1])

print(list2)

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

相关文章:

python - 检查时间戳是否在两列之间

python - 无法将多维数组传递给 *.pyx 中的 C 函数

python - 以两种方式遍历列表但无法理解行为

java - Java中根据输入参数的类型决定如何执行方法

Python 列表排序为预期输出创建不同的顺序

python - 从python中的二维数组中随机采样子数组

Python 连接 Oracle 数据库

python - 如何通过 rpyc 获取命令的输出?

python - 在列表理解中解包列表

python - 如何对坐标列表进行排序?