首页 > 解决方案 > 制表 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)

标签: pythonjsonbotstelegram

解决方案


要对列表中的项目进行配对,您可以从列表中创建一个迭代器,将迭代器与自身压缩,并通过压缩对使用列表推导来迭代器:

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.


推荐阅读