简体   繁体   English

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

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

I am trying to iterate through a list of several words. 我试图遍历几个单词的列表。 If a certain letter is present it will replace that letter and add a word to the existing word. 如果存在某个字母,它将替换该字母并将一个单词添加到现有单词中。 But it will only work on words in the list that have that letter. 但它仅适用于列表中带有该字母的单词。

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]

This will add 'sample' to everything, i dont know how to make it only add 'sample' to cells with the letter "s". 这将为所有内容添加“样本”,我不知道如何使其仅将“样本”添加至字母为“ s”的单元格。

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

Should show 应该显示

list2 = [06h', '12d', '05h', '04sample', '12sample', '12c']

Use a comprehension checking if the strings ends in s : 使用理解检查字符串是否以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']

you can use find and can replace with samples 您可以使用查找并可以替换为示例

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)

would work as well. 也会工作。 map applies a function to every element of a list and returns a list of the results. map将函数应用于列表的每个元素,并返回结果列表。

Python is full of tools for working with lists. Python充满了使用列表的工具。

暂无
暂无

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

相关问题 如何遍历列表以查找一定长度的单词? - How to iterate through a list finding words of a Certain length? 如何用 Python 替换列表中的单词 - How to replace words in list with Python 将单词添加到包含字符串中某些字母的列表中 - Adding words to a list which contains certain letters within a string 假设我知道某些字母,如何过滤一个单词列表作为秘密单词的可能候选者 - How to filter a list of words as likely candidates for a secret word, given that I know certain letters 如何仅替换文件中的某些单词 - how to replace only certain words in a file 如何使用 replace() 替换列表中的单词? - How to use replace() to replace words in a list? 快速查找单词列表是否包含至少一个以某些字母开头的单词(不是“查找所有单词”!) - Fast way to find if list of words contains at least one word that starts with certain letters (not "find ALL words"!) 如何在for循环中匹配以特定字母序列开头的所有单词? (Python) - How to match all words starting with a certain sequence of letters in a for loop? (Python) 如何使用Python在txt文件中搜索包含某些字母的单词? - How to search for words containg certain letters in a txt file with Python? 如何将一个包含多个单词的字符串拆分成一个包含一定数量单词的字符串的列表? - How to split a string of multiple words into a list with strings of a certain number of words?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM