我的问题是类似excel formula to replace or stubstitute only text that starts with a certain letter但我需要在Python代码。我试图做的嵌套if但它只是取代了第一个字符而不是整个元素。
还元素是字母数字
List= ['F43.9', 'F53.2', 'H10.9', 'H60.9',
'S83.6', 'S01.88', 'J18.9', 'K35.9', 'S42.20', 'J06.9'....]
所以我期望的输出是:
列表= [ 'QWE', 'QWE', '等于', '等于', '慢性', '慢性', '容易', '优先级', '慢性', '容易',....]
在这里我需要替换所有的值,如F
开始F43.9,F53.2,etc
。与"qwe"
。同样地,对于不同的字母表。有与600个唯一值列表30000元。
你的新的编辑表示要替换整个单词。简单地检查元素startswith()
你期望的字符,然后用所需的字符串替换它。这能有点健壮,虽然,所以你可能是一本字典更好。
for i in range(0, len(list)):
if list[i].startswith('F'):
list[i] = 'qwe'
elif list[i].startswith('H'):
list[i] = 'equals'
elif list[i].startswith('S'):
list[i] = 'chronic'
map = {
'F': 'qwe',
'H': 'equals'
'S': 'chronic'
# etc etc
}
for i in range(0, len(list)):
if list[i][0] in map.keys(): # check if first char is a key in map
list[i] = map[list[i][0]] # if it is, replace list[i] with the value in map
也许可以用list-comprehension
它
List = ['qwe'+i[1:] if i.startswith('F') else i for i in List]
通过使用列表解析,我们可以通过执行实现这一目标:
new_list = ['qwe' + List[i][1:] if List[i].startswith('F') else List[i] for i in range(len(List)) ]
print(new_list)
['qwe43.9','qwe53.2','H10.9','H60.9', 'S83.6','S01.88','J18.9','K35.9','S42.20',
'J06.9']
你可以代替字母“F”为您要更换的开头字母串中的任何其他字母。
尝试这个:
for i in range(0, len(list)):
if list[i].startswith('F'):
list[i] = 'qwe'
elif list[i].startswith('H'):
list[i] = 'chronic'
elif list[i].startswith('S'):
list[i] = 'liable'
else list[i].startswith('J'):
list[i] = 'priority'
等等...