【问题标题】:Is there a Python function for creating variables? [duplicate]是否有用于创建变量的 Python 函数? [复制]
【发布时间】:2021-05-31 22:19:57
【问题描述】:

我正在做一个 python 项目,我想在其中创建几个包含相同信息的变量;但是,我自己无法解决这个问题。

而不是写:

a = 1
b = 1
c = 1

等等,我想自动化这个过程。 以下是我迄今为止尝试过的一些示例:

示例 1:

random.randint(0, 100) = 1

示例 2:

str(random.randint(0, 100)) = 1

示例 3:

class makevariable:
  random = 0

setattr(makevariable, 'random', random.randint(0, 1000)) 
getattr(makevariable, 'random') = 1

【问题讨论】:

  • 我认为你想要的是一个列表,而不是一堆单独命名的变量。例如,要列出 10 个 1,您可以写为 foo = [1] * 10foo = [1 for _ in range(10)]
  • ... 可能更像foo = [randint(0, 1000) for _ in range(10)]

标签: python variable-names


【解决方案1】:

您可能需要list(可能是字典,dict)。

import random

my_vars = [random.randint(0, 100), random.randint(0, 100), random.randint(0, 100)] # a list
print(my_vars)

# alternatively..
my_vars = [] # an empty list
for ix in range(3):
    my_vars.append(random.randint(0, 100)) # add one element at a time
print(my_vars)

# ... or more smoothly constructed using comprehension
my_vars = [random.randint(0, 100) for ix in range(3)]
print(my_vars)

# look at just the first element
print(my_vars[0]) # note the list is zero indexed

# look at just the second element
print(my_vars[1])

# how many elements?
print( len(my_vars) )

# doesn't have to be the same type
my_vars = ['fred', 3, 100/7, "Hello"]

# iterate across the list
for one_var in my_vars:
    print(one_var)

等等。 - 查看Python documentation 和教程。

【讨论】:

  • 指示的重复问题提供了很多关于字典的有用信息。从您的示例中,我怀疑您可能会发现列表更有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-26
  • 1970-01-01
  • 2015-12-22
  • 2020-06-06
  • 2012-09-04
  • 2020-08-06
  • 2019-10-23
相关资源
最近更新 更多