使用连续名称打印变量的问题

时间:2018-07-11 11:13:01

标签: python

我是Python的新手,所以提前致歉。这是我遇到问题的代码:

x = 1

v1 = "First"
v2 = "Second"
v3 = "Third"
v4 = "Forth"
v5 = "Fifth"
v6 = "Sixth"
v7 = "Seventh"
v8 ="Eighth"
v9 = "Ninth"
v10 = "Tenth"

for x in range (1,11):
    print("v"+str(x))

这是返回的结果:

v1
v2
v3
v4
v5
v6
v7
v8
v9
v10

这就是我想要返回的结果:

First
Second
Third
Fourth
Fifth
Sixth
Seventh
Eighth
Ninth
Tenth

我如何打印名称越来越多的变量的内容?

9 个答案:

答案 0 :(得分:3)

for i in range(1, 11):
    print(locals()['v' + str(i)])

顺便说一句,这很糟糕。了解dictionaries

答案 1 :(得分:3)

尝试一下。只需将字符串存储在列表中并打印:

x = 1
store_1 = ["First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eighth", "Ninth","Tenth"] 
for x in store_1:
    print(x)

答案 2 :(得分:2)

我建议不要将所有值存储在list中,而不是将每个值存储在自己的变量中:

存储在列表中-

v = ["First", "Second", "Third"...] 

要访问此列表中的值,您将使用与此类似的语法(请注意,在python中,列表从索引零开始):

str = v[0]
# str will now be equal to "First"

现在,当您使用range时,会生成一个数字序列,可用作列表的索引:

for x in range (0,11):
    print(v[x])

因此,此循环将求值以打印以下命令:

print(v[0]) # "First"
print(v[1]) # "Second"
print(v[2]) # "Third"
...

访问特定索引处的列表将返回存储在相同索引处的值。


请注意,我将range()更改为从零开始,因为如果您从1开始,则会跳过索引为零的第一个元素。另外,可以通过将列表的长度用作范围的"end"索引来进一步改进此代码:

v = ["First", "Second", "Third"...] 
num_items = len(v)
for x in range(0, num_items):
    print(v[x])

使用此方法,您的v列表可以具有不同的大小,并且您无需对循环进行任何更改。


感谢helpful commenter的最后一点:范围函数实际上使用零作为默认的第一个值,因此可以进一步简化循环:

for x in range(num_items):
    print(v[x])

答案 3 :(得分:1)

您可以选择使用Marco指出的使用本地人,也可以像-

那样使用eval
for i in range(1, 11):
    print eval("v{}".format(i))

但是解决此问题的更好方法是使用列表或字典

答案 4 :(得分:1)

在这里也可以选择评估

for i in range (10):
    print(eval('v{}'.format(i+1)))

答案 5 :(得分:1)

保持简单,创​​建列表并使用循环进行遍历。

Numbers = ["First", "Second","Third","Forth", "Fifth", "Sixth","Seventh","Eighth", "Ninth", "Tenth"]

for number in Numbers:
    print number

输出:

第一 第二 第三 第四 第五 第六 第七 第八 第九 第十

答案 6 :(得分:0)

您可以使用globals()访问全局变量。

x = 1

v1 = "First"
v2 = "Second"
v3 = "Third"
v4 = "Forth"
v5 = "Fifth"
v6 = "Sixth"
v7 = "Seventh"
v8 ="Eighth"
v9 = "Ninth"
v10 = "Tenth"

for x in range (1,11):
    print(globals()["v"+str(x)])

这将输出:

First
Second
Third
Forth
Fifth
Sixth
Seventh
Eighth
Ninth
Tenth

答案 7 :(得分:0)

使用列表:

v1 = "First"
v2 = "Second"
v3 = "Third"
v4 = "Forth"
v5 = "Fifth"
v6 = "Sixth"
v7 = "Seventh"
v8 ="Eighth"
v9 = "Ninth"
v10 = "Tenth"
for x in [v1,v2,v3,v4,v5v6,v7,v8,v9,v10]:
    print(x)

答案 8 :(得分:0)

您还可以将项作为键值对存储在字典中:

lst = ["First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eighth", "Ninth","Tenth"]

d = {"v" + str(i+1): e for i, e in enumerate(lst)}
# {'v1': 'First', 'v2': 'Second', 'v3': 'Third', 'v4': 'Fourth', 'v5': 'Fifth', 'v6': 'Sixth', 'v7': 'Seventh', 'v8': 'Eighth', 'v9': 'Ninth', 'v10': 'Tenth'}

# print key -> value pairs
for v in d:
    print(v, "->", d[v])

其中提供了以下映射:

v1 -> First
v2 -> Second
v3 -> Third
v4 -> Fourth
v5 -> Fifth
v6 -> Sixth
v7 -> Seventh
v8 -> Eighth
v9 -> Ninth
v10 -> Tenth