如何在Python中将从循环中检索的值存储在不同的变量中?

Yas*_*wal 1 python iteration for-loop python-2.7

只是一个简单的问题.
假设,我有一个简单的for循环之类的

for i in range(1,11):
    x = raw_input() 
Run Code Online (Sandbox Code Playgroud)

我想在不同的变量中存储我将在整个循环中获得的x的所有值,以便稍后当循环结束时我可以使用所有这些不同的变量.

Ana*_*nth 6

您可以将每个输入存储在一个列表中,然后在需要时访问它们。

inputs = []
for i in range(1,11);
    x = raw_input()
    inputs.append(x)


# print all inputs
for inp in inputs:
    print(inp)

# Access a specific input
print(inp[0])
print(inp[1])
Run Code Online (Sandbox Code Playgroud)


jho*_*e89 6

在循环之前创建一个列表,并在迭代时将x存储在列表中:

l=[]
for i in range(1,11):
    x = raw_input()
    l.append(x)
print(l)
Run Code Online (Sandbox Code Playgroud)


Ahs*_*que 5

您可以与他们形成列表。

your_list = [raw_input() for _ in range(1, 11)]
Run Code Online (Sandbox Code Playgroud)

要打印列表,请执行以下操作:

print your_list
Run Code Online (Sandbox Code Playgroud)

要遍历列表,请执行以下操作:

for i in your_list:
    #do_something
Run Code Online (Sandbox Code Playgroud)

  • 为什么要投票?愿意发表评论吗? (2认同)