在括号中存储列表元素

Storing list elements in brackets

我有一个列表,我正在尝试用括号中的元素填充它。在最简单的形式中,我的问题是我希望 example=([]) 变成 example=([('a','b'),('c','d')]).

更明确地说,我正在尝试将下面的 运行nable 代码片段转换为一个函数。但是我无法正确填写名为 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' 解决方案,但 none 有效,我想要一个 pythonic 解决方案。

您可以使用列表理解和 f-string:

def col(*args):
    """Should take `col['word', 'colour']` and return the word in that colour."""
    text = FormattedText([(f"class:{a[1]}", str(a[0])) for a in args])
    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)