比较和提取 python 2.7 中 2 个嵌套循环的元素
comparing and extracting elements of 2 nested loops in python 2.7
我有两个二维数组。
a=['the flower is red','butterflies are pretty','dog is a man best friend']
b=['231','01','034']
数组a
包含句子,而数组b
是我想从数组a
中提取的单词的索引。
例如,通过比较 b[0]
中的各个元素,即 231
,我想提取 is
、red
、flower
,其中 b[2]
, 我想提取 dog
, man
,best
.
所以,为了做到这一点,我必须逐字逐句地 a[]
元素,然后与 b[]
中的每个单独元素进行比较(例如读取 2
,3
,1
分别与a[i][j]
中的索引进行比较。)
因此,我需要两个二维数组循环并比较它们。 [我认为 4 个 for 循环]
for i in a:
x= i.split()
#x=one word
for idx, word in enumerate(x):
#idx= index of one word, word=one word
for i in b:
for y in i:
if y == idx: #comparing y which is a number with the index in a[]
print(word)
上面的代码不知何故不正确,我不知道哪里出了问题。
那么,获得所需结果的代码是什么?
for idx, s in enumerate(b):
r = []
for c in s:
r.append(a[idx].split()[int(c)])
print r
我有两个二维数组。
a=['the flower is red','butterflies are pretty','dog is a man best friend']
b=['231','01','034']
数组a
包含句子,而数组b
是我想从数组a
中提取的单词的索引。
例如,通过比较 b[0]
中的各个元素,即 231
,我想提取 is
、red
、flower
,其中 b[2]
, 我想提取 dog
, man
,best
.
所以,为了做到这一点,我必须逐字逐句地 a[]
元素,然后与 b[]
中的每个单独元素进行比较(例如读取 2
,3
,1
分别与a[i][j]
中的索引进行比较。)
因此,我需要两个二维数组循环并比较它们。 [我认为 4 个 for 循环]
for i in a:
x= i.split()
#x=one word
for idx, word in enumerate(x):
#idx= index of one word, word=one word
for i in b:
for y in i:
if y == idx: #comparing y which is a number with the index in a[]
print(word)
上面的代码不知何故不正确,我不知道哪里出了问题。 那么,获得所需结果的代码是什么?
for idx, s in enumerate(b):
r = []
for c in s:
r.append(a[idx].split()[int(c)])
print r