[英]How to use zip with different types?
我有以下代码#1:
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解决方案?
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'}]
您需要提供row
和cur
具体示例,但是我真的不认为zip
是问题。
如果您有一个整数列表,并且想要将其转换为字符串,则可以使用map
:
>>> map(str, [1, 2, 3])
['1', '2', '3']
这应该工作:
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.