在列表的索引中使用有条件的技术的名称是什么,但是条件中的变量是列表本身?如您所见,a是一个列表,但它用于检查列表b中的相应元素。
>>> a = [ 1, 2, 3]
>>> b = [7, 7,7]
>>> b[a==1] = 8
>>> b
[8, 7, 7]我使用numpy数组编写代码,并考虑查看核心Python是否包含相同的特性,结果发现它是存在的。我只是找不到它,因为我一点也不知道它叫什么。
编辑:我想知道什么叫什么,并解释了发生了什么,给出的评论表明,代码没有做我认为它正在做的事情。
为了清晰和精化,这是我为numpy输入的代码,并得到了类似于Python列表的替换。
>>> import numpy as np
>>> lower_green = np.array([0,180,0])
>>> upper_green = np.array([100,255,100])
>>> upper_green[lower_green == 0] = 7
>>> upper_green
array([ 7, 255, 7])发布于 2018-02-27 20:46:42
解构这个表达式,我们得到:
(False == 0) == True(a == 1) == False鉴于此,我们得出结论:
b[a == 1] == b[False] == b[0]发布于 2018-02-27 20:53:51
您想要做的事情可以实现如下(并不是在所有情况下都有效):
a = [ 1, 2, 3]
b = [7, 7, 7]
b[a.index(1)] = 8
output:
b = [8, 7, 7]但是,如果存在多个匹配元素,则方法index()只返回最低索引。因此,它不能在以下情况下工作:
a = [0, 1, 1]
b = [7, 7, 7]
b[a.index(1)] = 8
output:
b = [7, 8, 7] and not [7, 8, 8]但是,如果您想使用核心Python来完成这个任务,请看这里(从this的回答中获得帮助):
# first get all the indices of the matching elements
a = [0, 1, 1]
b = [7, 7, 7]
to_match = 1
to_replace = 8
ind = [n for n,x in enumerate(a) if x == to_match]
for i in ind:
b[i] = to_replace发布于 2018-02-27 20:56:23
https://stackoverflow.com/questions/49017577
复制相似问题