您好我的问题涉及很久以前某位用户的帖子:
Find and replace string values in Python list
针对我的具体情况。我有一个这样的清单:
appl = ['1', 'a', 'a', '2', 'a']
我想只用一个空的空格(保存“a”的位置)来替换“a”的“单个未知”实例。我不确定如何只为一个角色做这件事。有人可以帮忙吗?提前谢谢。
编辑:我应该提到我需要使用“索引”功能来首先找到“a”,因为它是一个变化的变量。然后我需要代替字符的代码。
EDIT2:很多人都假设索引是2,但我想指出的是该字符的索引是未知的。此外,“a”将在列表中出现约20次(将保留固定数字),但它们的位置将会发生变化。我想根据用户输入替换“a”。这是我正在使用的实际列表:
track [2] = ["|","@","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"]
@是一个charachter,|是一个边界,“”是一个空的空间。 用户输入输入以选择向右移动的数量,并显示一个新图像,显示@的新位置,并将@的旧位置替换为空格。列表的长度保持不变。这是我的问题的背景。
答案 0 :(得分:3)
您可以通过遍历列表并存储元素为'a'
的索引来找到第二个匹配项的索引,直到找到两个:
>>> appl = ['1', 'a', 'a', '2', 'a']
>>> idxs = (i for i,c in enumerate(appl) if c == 'a')
>>> next(idxs)
0
>>> appl[next(idxs)] = ''
>>> appl
['1', 'a', '', '2', 'a']
答案 1 :(得分:2)
您可以使用index来实现此目标,以及循环。 这是一个小功能:
def replace_element(li, ch, num, repl):
last_found = 0
for _ in range(num):
last_found = li.index(ch, last_found+1)
li[li.index(ch, last_found)] = repl
使用:
replace_element(appl, 'a', 2, ' ')
此方法特别好,因为当字符不在列表中时,它会抛出以下错误:
ValueError: 'a' is not in list
答案 2 :(得分:1)
appl = ['1', 'a', 'a', '2', 'a']
a_indices = [i for i, x in enumerate(appl) if x == 'a']
if len(a_indices) > 1:
appl[a_indices[1]] = ' '
答案 3 :(得分:1)
首先,找到第一次出现的值:
>>> appl = ['1', 'a', 'a', '2', 'a']
>>> first = appl.index('a')
>>> first
1
要查找第二个,请从第一个位置开始加一个:
>>> second = appl.index('a', first+1)
>>> second
2
然后将该位置设置为您想要的空间:
>>> appl[second] = ' '
>>> appl
['1', 'a', ' ', '2', 'a']
答案 4 :(得分:0)
您的列表("|"
,"@"
)似乎很短,"@"
始终存在,只是在不同的位置。在这种情况下,您可以在一行中替换"@"
列表中第一次出现的appl
:
appl[appl.index("@")] = " "
如果列表很大且项目可能不存在:
i = next((i for i, x in enumerate(lst) if x == item), None)
if i is not None:
lst[i] = replacement