繁体   English   中英

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

[英]How to iterate though a list of words and replace certain letters with words

我试图遍历几个单词的列表。 如果存在某个字母,它将替换该字母并将一个单词添加到现有单词中。 但它仅适用于列表中带有该字母的单词。

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

使用理解检查字符串是否以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']

您可以使用查找并可以替换为示例

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']    
   list2 =[]
   for x in list1:
         if 's' in x:
            x = x.replace('s', 'sample')
         list2.add(x)
map(lambda x: x.replace('s','sample'), list1)

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM