Python 2.7 比较和提取python 2.7中两个嵌套循环的元素
我有两个二维数组Python 2.7 比较和提取python 2.7中两个嵌套循环的元素,python-2.7,nested-loops,Python 2.7,Nested Loops,我有两个二维数组 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[]中的每个元素进行比较(例如,分别
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]
中的索引进行比较)
因此,我需要两个2d数组循环并比较它们。[4对于循环,我认为]
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)
上面的代码有点不正确,我不知道哪里出了问题。
那么,获得想要的结果的代码是什么?问题是什么?我已经尝试了这段代码,这几乎就是我想要的结果。但是,是否可以将其作为[]编码回原始索引中?例如:result=['is red flower','butterflies are','dog man best'](注意,这些词没有标记,而是在一个索引中重新梳理成一句话)@Lily我恐怕不明白你的问题;你能发布预期的结果吗?我希望结果是数组的形式,而不会丢失数组中的原始索引。结果=[‘是红花’、‘蝴蝶是’、‘狗男人最好’](注意,这些词没有标记,而是在一个索引中重新梳理成一句话)好的,非常感谢您的帮助@memo。令人惊讶的是,你可以用一种更简单的方式来编码,而不是像我这样的长代码块。
for idx, s in enumerate(b):
r = []
for c in s:
r.append(a[idx].split()[int(c)])
print r