我在Python中有两个迭代,我想成对地遍历它们:
foo = (1, 2, 3)
bar = (4, 5, 6)
for (f, b) in some_iterator(foo, bar):
print "f: ", f, "; b: ", b
Run Code Online (Sandbox Code Playgroud)
它应该导致:
f: 1; b: 4
f: 2; b: 5
f: 3; b: 6
Run Code Online (Sandbox Code Playgroud)
一种方法是迭代索引:
for i in xrange(len(foo)):
print "f: ", foo[i], "; b: ", b[i]
Run Code Online (Sandbox Code Playgroud)
但这对我来说似乎有点不合时宜.有没有更好的方法呢?
我有一行从多个列表中提取变量,我希望它避免出现StopIteration错误,以便它可以移动到下一行.目前我正在使用break函数,这避免了StopIteration,但只给了我列表中的第一项,如果我要将它打印出来,它会留下一个空白行.
以下是我的两个具有相同问题的迭代.
def compose_line5(self, synset_offset, pointer_list):
self.line5 = ''''''
for item in pointer_list:
self.line5 += '''http://www.example.org/lexicon#'''+synset_offset+''' http://www.monnetproject.eu/lemon#has_ptr '''+pointer_list.next()+'''\n'''
break
return self.line5
def compose_line6(self, pointer_list, synset_list):
self.line6 = ''''''
for item in synset_list:
self.line6 += '''http://www.example.org/lexicon#'''+pointer_list.next()+''' http://www.monnetproject.eu/lemon#pos '''+synset_list.next()+'''\n'''
break
return self.line6
Run Code Online (Sandbox Code Playgroud)
这是我没有休息时得到的错误:
Traceback (most recent call last):
File "wordnet.py", line 225, in <module>
wordnet.line_for_loop(my_file)
File "wordnet.py", line 62, in line_for_loop
self.compose_line5(self.synset_offset, self.pointer_list)
File "wordnet.py", line 186, in compose_line5
self.line5 += '''http://www.example.org/lexicon#'''+self.synset_offset+''' http://www.monnetproject.eu/lemon#has_ptr '''+self.pointer_list.next()+'''\n'''
StopIteration
Run Code Online (Sandbox Code Playgroud)
有没有快速解决这个问题,或者我必须捕获我使用iter()的每个方法的异常?
现在我想建立一个包含100*50二维点的列表.我尝试过以下方法:
[(x+0.5, y+0.5) for x, y in zip(range(100), range(50))]
Run Code Online (Sandbox Code Playgroud)
这只给我50*50分.我在这个答案中找到了解释这一点的原因
对于zip,新列表的长度与最短列表的长度相同.
什么是最100*50正确的方式来正确获得我想要的点?
我想将特定金额分享/分配给两个Python列表的成员.list1的成员每个都有两个共享,而list2的成员每个都有一个共享,然后打印出结果,并分配名称和值.以下是我的示例代码:
reminder = float(85000)
list1 = ['Designer', 'Coder', 'Supervisor']
list2 = ['Artist', 'Attendant', 'Usher]
for i,j in list1 and list2:
print(i, (reminder/9)*2)
print(j, (reminder/9)*1)
Run Code Online (Sandbox Code Playgroud)
当我运行上面的代码时,我得到了一个例外:
Traceback (most recent call last):
File "C:\Python33\reminder.py", line 6, in <module>
for i,j in list1 and list2:
ValueError: too many values to unpack (expected 2)
Run Code Online (Sandbox Code Playgroud)
我搜索过相同主题的先前帖子,但无法找到解决方案.
我该怎么办呢?
如果没有枯燥乏味的for-loops,你会如何进行重叠列表?
功能:
l1=[1,2,3]
l2=['a','b','c']
overlap(l1,l2) #[(1,'a'),(2,'b'),(3,'c')]
overlap(l2,l1) #[('a',1),('b',2),('c',3)]
Run Code Online (Sandbox Code Playgroud)