gpt4 book ai didi

python - 如何通过可变字符数扩展固定长度的 Python 列表?

转载 作者:太空狗 更新时间:2023-10-30 01:07:09 33 4
gpt4 key购买 nike

(如果有人可以建议更好的标题,一定要继续编辑)。

给定一个 list list1 其确切长度未知但已知其长度始终小于或等于 5,我希望填充一个单独的空 list list2,固定长度 5,包含 list1 中的值,如果 list2< 的大小用空字符串填充/em> 小于 5.

例如如果列表 1 = [1,2,3]

那么 list2 应该是 [1,2,3,'','']

等等。

所以:

if len(list1) < 5:
list2.extend(list1)
# at this point, I want to add the empty strings, completing the list of size 5

实现此目的的最巧妙方法是什么(确定要添加多少个空字符串)?

最佳答案

list2 = list1 + [''] * (5 - len(list1))

关于python - 如何通过可变字符数扩展固定长度的 Python 列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33030416/

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