如何遍历单词列表并用单词替换某些字母

问题描述 投票:0回答:4

我试图迭代几个单词的列表。如果存在某个字母,它将替换该字母并在现有单词中添加单词。但它只适用于列表中包含该字母的单词。

list1 = ['06h', '12d', '05h', '04s', '12s', '12c']
#list2 = list(x+'sample' for x in cards)

or 

for x in cards:
    if 's' in x:
        cards.append('ample')[0]

这将为所有内容添加“样本”,我不知道如何使它只添加“样本”到带有字母“s”的单元格。

list1 = [06h', '12d', '05h', '04s', '12s', '12c']
if "s" in list1:

应该显示

list2 = [06h', '12d', '05h', '04sample', '12sample', '12c']
python loops
4个回答
1
投票

如果字符串以s结尾,请使用理解检查:

>>> list1 = ['06h', '12d', '05h', '04s', '12s', '12c']
>>> [x + 'ample' if x.endswith('s') else x for x in list1]
['06h', '12d', '05h', '04sample', '12sample', '12c']

0
投票

您可以使用查找并可以替换样本

list1 = ['06h', '12d', '05h', '04s', '12s', '12c']
l2=[]
for item in list1:
    if item.find('s'):
        l2.append(item.replace('s','samples'))
    else:
        l2.append(item)
print(l2)

['06h', '12d', '05h', '04samples', '12samples', '12c']    

0
投票
   list2 =[]
   for x in list1:
         if 's' in x:
            x = x.replace('s', 'sample')
         list2.add(x)

0
投票
map(lambda x: x.replace('s','sample'), list1)

会工作的。 map将函数应用于列表的每个元素,并返回结果列表。

Python中充满了使用列表的工具。

© www.soinside.com 2019 - 2024. All rights reserved.