在列表中切换列表中不同数字的字符

时间:2015-05-05 15:05:02

标签: python list

我正在尝试将列表中的字符切换为该列表中给定位置的其他字符。对于前者 ["*","*","*","*","*",.....],更改位置[1,3,4,.....]中的字符 给定的字母,例如X.

因此["*","*","*","*","*","*"]变为["*",X,"*",X,X,"*"]

我试过这个:

def test():
letter="a"
secret="*****"
secret2=list(secret)
pos=[1,3]
y = 1
x = pos[y]
flag = 0
while flag < 2:
    secret2[x]=letter
    flag = (flag + 1)
    y = (y+1)
return secret2

但它只返回列表["*","*","*",A,"*"]

我将如何解决这个问题?是否能够通过课程更容易解​​决?在这种情况下,这个班级会是什么样子?

2 个答案:

答案 0 :(得分:4)

您可以在列表理解中使用enumerate

>>> l=[1,3,6]
>>> li=["*","*","*","*","*",'*','*']
>>> ['X' if i in l else j for i,j in enumerate(li)]
['*', 'X', '*', 'X', '*', '*', 'X']

答案 1 :(得分:2)

def substitute_at_positions(lst, positions, substitute):
  return [substitute if i in positions else lst[i] for i in xrange(len(lst))]

lst = ["","","","","","",""]
print lst
print substitute_at_positions(lst, {1,3,5}, "x")

打印

['', '', '', '', '', '', '']
['', 'x', '', 'x', '', 'x', '']
相关问题