【问题标题】:Python output each iteration of loop to a row of an arrayPython将循环的每次迭代输出到数组的一行
【发布时间】:2013-07-24 07:40:47
【问题描述】:

我很确定对此有一个简单的答案,但我完全被卡住了!

我有一个包含不同数量单词的列表,我正在尝试查看是否可以在文本文件中找到这些单词。 因此,如果我要查找的单词列表是:

stem=[[u'travail',u'electr'],[u'la',u'vou']]

然后我循环遍历词干列表的每个“行”中的每个单词,并尝试在文本文件中找到该单词。此代码返回单词匹配位置的索引。

for row in stem: 
       for j,i in enumerate(row):
           y=[match.start() for match in re.finditer(re.escape(i), lowe)]
              print y

输出:

[669, 2102, 5810]
   [1452, 2120, 5628]
   [1582, 2912, 3109, 5711]
   [605, 761, 882, 948, 1126, 1132, 1357, 1646, 1936, 2011, 2765, 3286, 3316, 3512, 3821, 3839, 3879, 4012, 4052,   4159, 4417, 4457, 4492, 4699, 4813, 4850, 4921, 4966, 4991, 4998, 5008, 5046, 5118, 5201, 5359, 5506, 5680]

我怎样才能得到这样的输出

 [[[669, 2102, 5810], [1452, 2120, 5628]], [[1582, 2912, 3109, 5711], [605, 761, 882, 948, 1126, 1132, 1357, 1646, 1936, 2011, 2765, 3286, 3316, 3512, 3821, 3839, 3879, 4012, 4052, 4159, 4417, 4457, 4492, 4699, 4813, 4850, 4921, 4966, 4991, 4998, 5008, 5046, 5118, 5201, 5359, 5506, 5680]]]

所以每一行的输出都在自己的列表中?谢谢!

【问题讨论】:

  • 另外,你的enumerate 有什么意义?我没有看到你在任何地方使用j,所以看起来你应该能够做到for i in row:(然后我可能会将变量名i更改为column或更清楚一点)
  • 您必须使用一个结果列表,您将在其中附加每个子列表。

标签: python arrays iteration output


【解决方案1】:

如果我理解正确,应该这样做:

output = []
for row in stem: 
   current = []
   output.append(current)
   for j,i in enumerate(row):
       y=[match.start() for match in re.finditer(re.escape(i), lowe)]
       current.append(y)

print output

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    相关资源
    最近更新 更多