【发布时间】:2022-08-08 09:18:14
【问题描述】:
我有一个包含字符串的简单列表“段落”。目标是将这些拆分的单词连接成每行 5 个单词的行。使用模数 5(针对索引值 + 1 进行简化)作为测试何时添加换行符。
由于我无法理解的原因,它工作正常,除非它突然决定跳过 5 的倍数。我无法弄清楚它为什么不一致。神秘地跳过索引 40、45 和 55。
for word in passage:
indx = passage.index(word) # dump into variable \"indx\" for convenience
if (indx+1) %5 == 0: # act every 5th element of list
passage[indx] = f\"{word}\\n{indx+1}\" # add line break and index number to element
print(passage)
print()
final = \" \".join(passage)
print(final)
更改列表输出:
[\'When\', \'in\', \'the\', \'Course\', \'of\\n5\', \'human\', \'events,\', \'it\', \'becomes\', \'necessary\\n10\', \'for\', \'one\', \'people\', \'to\', \'dissolve\\n15\', \'the\', \'political\', \'bands\', \'which\', \'have\\n20\', \'connected\', \'them\', \'with\', \'another,\', \'and\\n25\', \'to\', \'assume\', \'among\', \'the\', \'powers\\n30\', \'of\', \'the\', \'earth,\', \'the\', \'separate\\n35\', \'and\', \'equal\', \'station\', \'to\', \'which\', \'the\', \'Laws\', \'of\', \'Nature\', \'and\', \'of\', \"Nature\'s\", \'God\', \'entitle\', \'them,\\n50\', \'a\', \'decent\', \'respect\', \'to\', \'the\', \'opinions\', \'of\', \'mankind\', \'requires\', \'that\\n60\', \'they\', \'should\', \'declare\', \'the\', \'causes\\n65\', \'which\', \'impel\', \'them\', \'to\', \'the\', \'separation.\']
和 \"joined\" 输出为字符串:
When in the Course of
5 human events, it becomes necessary
10 for one people to dissolve
15 the political bands which have
20 connected them with another, and
25 to assume among the powers
30 of the earth, the separate
35 and equal station to which the Laws of Nature and of Nature\'s God entitle them,
50 a decent respect to the opinions of mankind requires that
60 they should declare the causes
65 which impel them to the separation.
想法?
很抱歉没有包括原始列表,ewong:
[\'When\', \'in\', \'the\', \'Course\', \'of\', \'human\', \'events,\', \'it\', \'becomes\', \'necessary\', \'for\', \'one\', \'people\', \'to\', \'dissolve\', \'the\', \'political\', \'bands\', \'which\', \'have\', \'connected\', \'them\', \'with\', \'another,\', \'and\', \'to\', \'assume\', \'among\', \'the\', \'powers\', \'of\', \'the\', \'earth,\', \'the\', \'separate\', \'and\', \'equal\', \'station\', \'to\', \'which\', \'the\', \'Laws\', \'of\', \'Nature\', \'and\', \'of\', \"Nature\'s\", \'God\', \'entitle\', \'them,\', \'a\', \'decent\', \'respect\', \'to\', \'the\', \'opinions\', \'of\', \'mankind\', \'requires\', \'that\', \'they\', \'should\', \'declare\', \'the\', \'causes\', \'which\', \'impel\', \'them\', \'to\', \'the\', \'separation.\']
我会检查枚举。 (刚开始使用 Python。对不起,如果我看起来很迟钝。)
Eduardo Reis,感谢关于重复数组元素会导致某种索引问题的建议。我会调查的。
-
欢迎来到堆栈溢出。你的样本输入是什么?
-
写
print(indx, word)会比写这个问题要快。 -
index本质上总是错误的工具。使用enumerate。 -
使用
for indx, word in enumerate(passage):。请注意,在您的情况下,如果word在段落中重复,您将得到错误的结果 -
欢迎来到堆栈溢出。出现问题是因为
.index发现首先列表中给定单词的索引。它不可能给你“当前单词”的索引,因为你是调用方法;它没有循环的上下文,它只看到单词,然后在列表中查找。解决方案是使用一个循环结构循环时为您提供索引,就像在第一个链接的副本中一样。