簡體   English   中英

For循環Python中的元組和迭代器

[英]Tuple and Iterators in For Loops Python

通過Toby Segaran編寫的Programming Collective Intelligence,這部分代碼使我有些困惑。 sqlite select語句用python2編寫,返回一個迭代器,然后他在for循環中檢索到(urlid,),然后又在(linker)中,我不明白他為什么使用這種語法,這是一個元組嗎? 目的是什么? 非常感謝。

for i in range(iterations):
  print "Iteration %d" % (i)
  for (urlid,) in self.con.execute('select rowid from urllist'):
    pr=0.15
    # Loop through all the pages that link to this one
    for (linker,) in self.con.execute(
    'select distinct fromid from link where toid=%d' % urlid):
       # Get the PageRank of the linker
       linkingpr=self.con.execute(
       'select score from pagerank where urlid=%d' % linker).fetchone( )[0]

self.con.execute('select rowid from urllist')在每次迭代時返回1個元素的列表(或元組)。

這個語法:

for (urlid,) in self.con.execute('select rowid from urllist'):

是一種從包含一個元素的傳入元組/列表中解壓縮標量值urlid的快速方法。

最后的逗號用於區分元組語法和用於保護運算符優先級的簡單括號。

沒有這種語法,我們將不得不做:

for urlid_list in self.con.execute('select rowid from urllist'):
    urlid = urlid_list[0]

解壓縮list也可以,在這種情況下無需逗號:

for [urlid] in self.con.execute('select rowid from urllist'):

這是非常不尋常的語法,但是它是有效的。

需要了解的是,即使在該結果中只有一列,SQL execute語句也總是每行返回一個元組。 所以結果看起來像這樣:

[(1,), (2,), (3,), (4,)]

這是單項元組的列表。

什么代碼正在做的是拆包每個元組,這樣urlidlinker都指向每個元組的單個元素。

似乎self.con.execute返回具有一個元素的可迭代元組。 示例中的for循環遍歷每個元組,並將單個元素元組解包為一個變量。

嘗試將for (urlid,) in self.con.execute替換for (urlid,) in self.con.executefor urlid in self.con.execute並在下一行print (type (urlid)) 這應該給tuple ,因為原始將在其中打印元素的類型。

您也可以嘗試使用此方法來顯示正在發生的情況:

letters = [('a',), ('b',), ('c',)]

for (letter,) in letters:
    print(letter)

for letter_tuple in letters:
    print(letter_tuple)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM