2017-09-06 21 views
-1

我有以下代碼#1:如何使用不同類型的zip?

await cur.execute(query) 
async for row in cur: 
    if row[1] not in banned_doorbots: 
     result.append({ 
      'ding_id': row[0], 
      'doorbot_id': row[1], 
      'kind': row[2] 
}) 
return result 

我這重構爲2:

await cur.execute(query) 
keys = ('ding_id', 'doorbot_id', 'kind') 
return [dict(zip(keys, row)) async for row in cur 
      if row[1] not in banned_doorbots] 

但現在我有一個問題,我ding_id應該包含str類型, 這樣'ding_id': str(row[0])

如何使用我的#2的解決方案?

+0

你有'row'任何的例子嗎?現在,測試你的代碼是不可能的。 –

+0

你們是不是要排轉換'[0]'爲一個字符串,或者是'行[0]'一個字符串,當你不希望它是什麼? – jwodder

+0

@jwodder轉換'行[0]'爲字符串 – petrush

回答

0

這應該工作:

return [dict(zip(keys, [str(row[0])] + row[1:])) async for row in cur 
      if row[1] not in banned_doorbots] 

如果row是一個元組,轉換成一個列表第一:

return [dict(zip(keys, [str(row[0])] + list(row[1:]))) async for row in cur 
     if row[1] not in banned_doorbots] 
+0

你似乎有一個括號缺失。 – ekhumoro

+0

謝謝。複製粘貼問題。固定。 –

+0

我有以下錯誤:'類型錯誤:只能串聯列表(不是「元組」),以list' – petrush

2

zip不關心類型,肯定整數不轉換爲字符串。唯一重要的是參數應該是可迭代的(在你的例子中似乎是這種情況)。儘管這些迭代器中的元素保持不變。

keys = ('ding_id', 'doorbot_id', 'kind') 
cur = [[1, 1000, 'a'], [2, 1002, 'b']] 
print([dict(zip(keys, row)) for row in cur]) 
# [{'ding_id': 1, 'doorbot_id': 1000, 'kind': 'a'}, {'ding_id': 2, 'doorbot_id': 1002, 'kind': 'b'}] 

你需要提供的rowcur具體的例子,但我真的不認爲zip是問題。

如果你有一個整數的列表,並希望將其轉換爲字符串,您可以使用map

>>> map(str, [1, 2, 3]) 
['1', '2', '3'] 
相關問題