我有一个由空格分隔的单词组成的字符串(所有单词都是唯一的,没有重复的)。我将此字符串转换为列表:
s = "#one cat #two dogs #three birds"
out = s.split()
并计算创建了多少个值:
^{pr2}$然后我试着从列表中删除所有内容:
for x in out:
out.remove(x)
然后再数数:
print len(out) # Says 96
为什么有人会说96而不是0?在
更多信息
每行以“#”开头,实际上是一对空格分隔的单词:第一行是键,第二行是值。在
所以,我要做的是:
for x in out:
if '#' in x:
ind = out.index(x) # Get current index
nextValue = out[ind+1] # Get next value
myDictionary[x] = nextValue
out.remove(nextValue)
out.remove(x)
问题是我不能将所有键、值对都移到字典中,因为我只迭代96个项。在
你没说具体的。你为什么要删除列表中的所有内容?如果你需要做的只是清除列表,为什么不直接这样做:
至于for循环中实际发生了什么:
我认为最好借助一个插图来展示。在
现在,假设您有一个
iterable object
(例如list
),如下所示:当你做
^{pr2}$for x in out
时,它会创建内部索引器,如下所示(我用符号^
来说明):通常的情况是:当您完成循环的一个循环时,索引器向前移动,如下所示:
因此,当您执行
remove
操作时,内部会发生以下情况:请注意,那里只有3个周期,而不是6个周期(!!)(这是原始列表中元素的数目)。这就是为什么你留下了原来的
len
的一半,因为当你在每个循环中移除一个元素时,完成循环所需的周期数。在如果要清除列表,只需执行以下操作:
或者,如果要逐个删除元素,则需要以相反的方式进行操作,即从末尾到开头。使用
reversed
:现在,为什么
reversed
会起作用?如果索引器继续前进,那么reversed
是否也不应该工作,因为元素的数量在每个循环中减少了一个?在不,不是那样的
举例来说,这是通常发生的情况:
因此,当每个周期执行一次删除操作时,它不会影响索引器的工作方式:
希望这张图能帮助你了解内部的情况。。。在
我想你真的想要这样的东西:
这个代码在做什么?让我们把它分解。首先,我们按空格将
s
拆分为out
。在接下来我们迭代
out
中的对,称它们为“x, y
”。这些对成为元组/对的list
。dict()
接受大小为两个元组的列表,并将它们视为key, val
。在以下是我尝试的结果:
^{pr2}$相关问题 更多 >
编程相关推荐