英文:
Python, append string as value
问题
你好,以下是翻译好的部分:
我是新手学习Python,有没有一种方法可以在Python中将字符串附加为值。
例如:
b0 = str("123")
b1 = str("234")
b2 = str("345")
现在很容易。但在我的特殊情况下,我必须做类似这样的事情。
a = []
for i in range(0, 3):
z = str("b") + str(i)
a.append(z)
我的计划是当我打印(a)时,它应该类似于['123', '234', '345']。实际上,它的输出是['b0', 'b1', 'b2']。
那么,我应该如何修复这个问题。
英文:
I am new to python, is there a way to append string in python as value.
For example:
b0 = str("123")
b1 = str("234")
b2 = str("345")
Easy for now. But in my special case, I have to doing somethings like this.
a = []
for i in range (0,3):
z = str("b") + str("i")
a.append(z)
My plan is when I print(a), it should somethings like ['123', '234', '345']. In fact, it doing like this['b0', 'b1', 'b2'].
So, how can I fix this.
答案1
得分: 1
使用字典。不要在不需要的地方使用`str`。
var['b0'] = "123"
var['b1'] = "234"
var['b2'] = "345"
a = []
for i in range(3):
a.append(var[f"b{i}"])
<details>
<summary>英文:</summary>
Use a dictionary. Don't use `str` where it isn't required.
var['b0'] = "123"
var['b1'] = "234"
var['b2'] = "345"
a = []
for i in range(3):
a.append(var[f"b{i}"])
</details>
# 答案2
**得分**: 0
```python
b_dict = {
'b0': '123',
'b1': '234',
'b2': '345'
}
a = []
for i in range(3):
z = 'b' + str(i)
a.append(b_dict.get(z))
英文:
b_dict = {
'b0': '123',
'b1': '234',
'b2': '345'
}
a = []
for i in range(3):
z = 'b' + str(i)
a.append(b_dict.get(z))
I'm also a beginner. She doesn't know why you're doing this, but that's one way I'm thinking about it, I'm going to use the dict.
答案3
得分: -1
a = []
for i in range(0, 3):
z = '%i%i%i' % (i, i+1, i+2)
a.append(z)
英文:
a=[]
for i in range (0,3):
z='%i%i%i' %(i,i+1,i+2)
a.append(z)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论