学习 Python:基于条件改变列表中的值

3

很抱歉问一个很基础的问题,但实际上这是一个由两个部分组成的问题:

  1. Given a list, I need to replace the values of '?' with 'i' and the 'x' with an integer, 10. The list does not always have the same number of elements, so I need a loop that permits me to do this.

    a = ['1', '7', '?', '8', '5', 'x']
    
  2. How do I grab the index of where the value is equal to '?'. It'd be nice if this show me how I could grab all the index and values in a list as well.


1
当你说“keys and values”时,你实际上是指“indices and values”吗?键/值对只与字典一起使用,而不与列表一起使用。 - Dan Gerhardsson
7个回答

6

编写一个函数,并使用map()在每个元素上调用它:

def _replaceitem(x):
    if x == '?':
        return 'i'
    elif x == 'x':
       return 10
    else:
        return x

a = map(_replaceitem, a)

请注意,这将创建一个新列表。如果列表太大或出于其他原因不想这样做,则可以使用for i in xrange(len(a)):,然后在必要时更新a[i]
要从列表中获取(index,value)对,请使用enumerate(a),它返回产生这些对的迭代器。
要获取列表中包含给定值的第一个索引,请使用a.index('?')

5

仅因为还没有人提到,这是我最喜欢的非for循环用法,用于执行此类替换:

>>> a = ['1', '7', '?', '8', '5', 'x']
>>> reps = {'?': 'i', 'x': 10}
>>> b = [reps.get(x,x) for x in a]
>>> b
['1', '7', 'i', '8', '5', 10]

.get() 方法非常有用,而且比 if/elif 语句块更具扩展性。


4

对于1:

for i in range(len(a)):
    if a[i] == '?':
        a[i] = 'i'
    elif a[i] == 'x':
        a[i] = 10

对于第二个问题,你所说的“key”是指索引吗?
index = a.index('?')

3

2

这是一个名为“index”的函数:

>>> a = ['1', '7', '?', '8', '5', 'x']
>>> a.index('?')
2

2
你现在可以使用lambda。原始答案被翻译为"最初的回答"。
# replace occurrences of ?
a = map(lambda x: i if x == '?' else x, a)
# replace occurrences of x
a = list(map(lambda x: 10 if x == 'x' else x, a))

1
a = ['1', '7', '?', '8', '5', 'x']
for index, item in enumerate(a):
    if item == "?":
       a[index] = "i"
    elif item == "x":
       a[index = 10

print a

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接