如何将Python变量值赋值给指定列表元素
解决方案
有两种简单的实现方式,可根据你的场景选择:
方式一:直接索引修改(适合少量变量)
直接通过列表索引定位到目标元素,将变量转为字符串后拼接上去:
a = 2 b = 3 c = 1 command = ['entry1', 'entry2=', 'entry3=', 'entry4='] # 给对应位置的元素拼接变量值 command[1] += str(a) command[2] += str(b) command[3] += str(c) # 验证结果 print(command[1]) # 输出 entry2=2 print(command[2]) # 输出 entry3=3 print(command[3]) # 输出 entry4=1
方式二:循环批量处理(适合变量较多的场景)
把需要赋值的「列表索引-变量」配对后,通过循环统一处理,减少重复代码:
a = 2 b = 3 c = 1 command = ['entry1', 'entry2=', 'entry3=', 'entry4='] # 定义索引与变量的对应关系 targets = [(1, a), (2, b), (3, c)] for idx, value in targets: command[idx] += str(value)
补充说明
- 因为列表中的元素是字符串类型,所以需要用
str()把数值型变量转为字符串后再拼接; - 如果你的变量本身就是字符串,可以直接省略
str()转换。
内容的提问来源于stack exchange,提问作者ranjith
相关产品推荐
相关产品推荐

