python - 制表 Python 字典
问题描述
我正在努力在电报机器人上创建一个键盘。我想创建一些按钮。我有一个问题,我想创建一个向下滑动的键盘。有一个问题,使用json你可以通过代码n1创建它,但是在python中我找不到解决方案。那么我如何在 json (代码 n1)中转换 'lista = ["New York","Los Angeles","Miami","Toronto","Berlin","Rome"]'?
#code n1 (JSON)
{"keyboard": [[{"text": "New York"}, {"text": "Los Angeles"}],
[{"text": "Miami"}, {"text": "Toronto"}],
[{"text": "Berlin"}, {"text": "Rome"}]]}
#code2
import json
import time
from pprint import pprint
import telepot
from telepot.loop import MessageLoop
bot = telepot.Bot("token")
lista = ["New York","Los Angeles","Miami","Toronto","Berlin","Rome"]
kdict = []
for i in lista:
kdict.append({"text": i})
print(kdict)
keyboard = {"keyboard": [kdict]}
def handle(msg):
content_type, chat_type, chat_id = telepot.glance(msg)
print(content_type, chat_type, chat_id)
if content_type == "text":
bot.sendMessage(chat_id, msg["text"], reply_markup=keyboard)
MessageLoop(bot, handle).run_as_thread()
while 1:
time.sleep(10)
解决方案
要对列表中的项目进行配对,您可以从列表中创建一个迭代器,将迭代器与自身压缩,并通过压缩对使用列表推导来迭代器:
seq = iter(lista)
[[{'text': i} for i in pair] for pair in zip(seq, seq)]
这将返回:
[[{'text': 'New York'}, {'text': 'Los Angeles'}],
[{'text': 'Miami'}, {'text': 'Toronto'}],
[{'text': 'Berlin'}, {'text': 'Rome'}]]
然后,您可以使用json.dumps
.
推荐阅读
- netbeans - Netbeans:如何将远程连接从一台计算机复制到另一台计算机?
- libreoffice-calc - Libreoffice Calc REGEX 如何获得第二场比赛?
- json - rust serde - 在反序列化时展平路径
- html - 用于滚动条的跨平台 CSS
- ios - 是否可以在没有源代码的情况下分发 iOS 应用程序
- html - 如何在父级内正确滚动内联元素
- powershell - Powershell 显示所有已停止的自动服务并尝试启动这些服务
- php - 改进 CSV 产品导入 -> Array Category Query by name
- amazon-s3 - 如何通过机器人框架运行 AWS CLI 命令?
- c# - 如何在 TableLayoutPanel 中找出控件的索引?