As the title says. ** How to get the value in the [name] column of B when the value in the list (A) of the one-dimensional array exists in the [ID] column of the list (B) of the two-dimensional array. ** ** The above is what I learned while playing with the slack api, and I've summarized it below.
A.list
print(name_list)
['U012JDYRD2T', 'U012X478FNZ']
B.list #It has been modified to make it easier to see.
print(data)
[['name', 'id'],
['Slackbot', 'USLACKBOT'],
['test_1', 'U012JDYRD2T'], #I want here
['test_5', 'U012JDYSN07'],
['kita', 'U012X478FNZ'],#I want here
['test_4', 'U012XQBE63X'],
['test_bot', 'U012YTNNPB5'],
['test_3', 'U012ZC8AQ8K'],
['tese_2', 'U013BQDLK6V']]
Expected results.py
print(result)
['test_1','kita']
1.py
result = []
for data_id in data:
if data_id[1] in name_list:
result.append(data_id[0])
(1) For loops [data_id in data]
, data is stored in data_id one by one.
② [if data_id [1] in name_list]
is a condition that the [id] column (data_id [1]) and name_list match.
③ [result.append (data_id [0])]
adds the [name] column (data_id [0]) to the list called [result]
1.py
result = []
result = [data_id[0] for data_id in data if data_id[1] in name_list]
The theory is the same as method 1. smart.
3.py
r = []
r2 = []
for i in data:
r = r + i
for i in name_list:
tmp = (r.index(i)) - 1
r2.append(r[tmp])
① Store data one by one in r. It is stored as ['name','id','Slackbot','USLACKBOT'…]
.
(2) Use the fact that name and id are stored in order.
In other words, the one before " U012X478FNZ "
is " kita "
, and the one before " U012JDYRD2T "
is " test_1 "
.
③ So, in [tmp = (r.index (i)) -1]
, you can get the index of" kita "immediately before that by [-1] from the index (number) of" U012X478FNZ ". it can.
④ And the value of the acquired index is added to [r2].
You need to understand more about loops and conditionals.
Recommended Posts