我有两个数组id
和x
,其中id
是一个唯一标识符,告诉我们x
中的值属于特定组。我想要做的是浏览x
中的值以查看是否满足某些条件,如果是,则打印相应的x
值。例如
id = np.array([1,1,1,2,2,2,3,3,3,4,4,4,5,5,5])
x = np.array([10,9,6,9,7,1,12,5,10,9,8,4,6,2,1])
counter = 1
for i in range(len(id)):
if id[i] == counter:
for j in range(i,len(id)):
if x[j] > 7:
continue
else:
print(id[i],x[j])
counter += 1
break
打印
1 6
2 7
3 5
4 4
5 6
现在,如果我们改为
id = np.array([1,1,1,2,2,2,3,3,3,4,4,4,5,5,5])
x = np.array([10,9,6,9,7,1,12,11,10,9,8,4,6,2,1])
输出
1 6
2 7
3 4
4 4
5 6
这不是我想要的输出,因为4
不在id
值3
的组中。所以我的问题是,如果if x[j] > 7:
值对应于代表它的x
值且不跳过该组,那么只有id
评估条件才会被评估?
答案 0 :(得分:3)
我有点困惑,但我会刺伤...... 字典有帮助吗?
id = np.array([1,1,1,2,2,2,3,3,3,4,4,4,5,5,5])
x = np.array([10,9,6,9,7,1,12,5,10,9,8,4,6,2,1])
dict = {}
for i in range(len(id)):
if id[i] not in dict:
dict[id[i]] = []
dict[id[i]].append(x[i])
#you now have a dict that is keyed by your group-id and has a list of values for that group.
for group in dict:
vals_in_group = dict[group]
for val in vals_in_group:
#check value? or just print
print group, val