[英]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.