如何使用不同类型的拉链?

2024-06-16 09:37:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码#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解决方案?你知道吗


Tags: inidforexecuteasyncifnotresult
2条回答

^{}不关心类型,当然也不会将整数转换为字符串。唯一重要的是,参数应该是iterables(在您的示例中似乎就是这样)。不过,这些iterables中的元素没有受到影响。你知道吗

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(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]

相关问题 更多 >