我有一个列表,我正在尝试用括号中的元素填充它。以最简单的形式,我的问题是我想example=([])
成为example=([('a','b'),('c','d')])
.
更明确地说,我试图将下面的可运行代码片段变成一个函数。但我无法让列表text
正确填写。这是工作的代码:
# import prompt toolkit
from prompt_toolkit import print_formatted_text
from prompt_toolkit.formatted_text import FormattedText
from prompt_toolkit.styles import Style
# My palette
my_palette = {"my_pink": '#ff1493', "my_blue": '#0000ff',}
# The text.
text = FormattedText([('class:my_pink', 'Hello '),('class:my_blue', 'World')])
# Style sheet
style = Style.from_dict(my_palette)
# Print
print_formatted_text(text, style=style)
这是我创建一个函数的尝试,它在某一时刻变成*args
了列表元素:
def col(*args):
"""Should take `col['word', 'colour']` and return the word in that colour."""
text = FormattedText([])
for a in args:
text_template = ("class:" + str(a[1]) + "', '" + str(a[0]))
text_template = text_template.replace("'", "")
text.append(text_template)
print(text) # Shows what is going on in the `text` variable (nothing good).
style = Style.from_dict(my_palette)
print_formatted_text(text, style=style)
该函数将使用以下内容运行:
col(["Hello", 'my_pink'], ["World", 'my_blue'])
该text
变量应该看起来像 的第一个示例text
,但是缺少括号并且逗号在字符串中,因此它看起来像这样:
text = FormattedText([('class:my_pink, Hello ', 'class:my_blue', 'World'])
而不是这样:
text = FormattedText([('class:my_pink', 'Hello '), ('class:my_blue', 'World')])
我尝试了进一步的操作,使用以下变体:
text = format(', '.join('({})'.format(i) for i in text))
但老实说,我无法理解我是如何在一个简单的问题上做出这样的猪耳朵的。我已经尝试了很多 'jammy' 解决方案,但都没有工作,我想要一个 pythonic 的解决方案。