gpt4 book ai didi

python - 如何获取未知长度的python列表中的所有元素?

转载 作者:太空宇宙 更新时间:2023-11-04 07:32:19 26 4
gpt4 key购买 nike

我有一个列表:

>>> my_list = ['a', 'b', 'c', 'd']

我有一个字符串,其中包含格式方法的 {} 标记:

>>> my_string = 'First element = "{}" and the Second element = "{}"'

我想像这样将 my_list 中的第一个元素插入到 my_string 中:

>>> print my_string.format(my_list[0], my_list[1])
First element = "a" and the Second element = "b"

但是,当我编写代码时:

  1. 我不知道my_string 中会有多少个{}
  2. 我不知道my_list中会有多少元素>
  3. 我知道#2 中的元素数量将大于或等于#1。

给定事实编号 1、2 和 3,我可以使用什么 python 表达式进行插值?

最佳答案

您可以使用 splat 运算符:(官方“解包参数列表”)

print(my_string.format(*my_list))

它将每个元素转换为另一个位置参数。

关于python - 如何获取未知长度的python列表中的所有元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45002699/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com