每次循环运行时如何将用户输入附加到不同的列表?
How to append user input to a different list every time a loop runs?
scores_h1 = []
scores_h2 = []
scores_h3 = []
scores_h4 = []
scores_h5 = []
scores_h6 = []
scores_h7 = []
scores_h8 = []
scores_h9 = []
for i in range(1,10):
value = int(input("Score: "))
string = f'scores_h{i}'
string.append(value)
我试图在循环第一次运行时将 value
附加到 scores_h1
。然后第二次到 scores_h2
然后第三次到 scores_h3
等等..有没有办法做到这一点?
您可以使用 collections
中的 defaultdict
得到 dict
的 lists
:
from collections import defaultdict
lists_dict = defaultdict(list)
for i in range(1,10):
value = int(input("Score: "))
lists_dict[f"list_{i}"].append(value)
print(dict(lists_dict))
输出:
{'list_1': [1], 'list_2': [2], 'list_3': [3], 'list_4': [4], 'list_5': [5], 'list_6': [6], 'list_7': [7], 'list_8': [8], 'list_9': [9]}
我不确定这是您真正想要的,但是下面的代码可以做到:
length = 9
lst = [[] for i in range(length)]
for i in range(length):
value = int(input("Score: "))
lst[i].append(value)
print(lst)
基本上你不需要9个独立的列表。你想要一个嵌套列表。然后你可以用相应的索引调用顶部列表中的每个列表。
输出可能如下所示:
[[1], [2], [3], [4], [5], [2], [3], [1], [3]]
scores_h1 = []
scores_h2 = []
scores_h3 = []
scores_h4 = []
scores_h5 = []
scores_h6 = []
scores_h7 = []
scores_h8 = []
scores_h9 = []
for i in range(1,10):
value = int(input("Score: "))
string = f'scores_h{i}'
string.append(value)
我试图在循环第一次运行时将 value
附加到 scores_h1
。然后第二次到 scores_h2
然后第三次到 scores_h3
等等..有没有办法做到这一点?
您可以使用 collections
中的 defaultdict
得到 dict
的 lists
:
from collections import defaultdict
lists_dict = defaultdict(list)
for i in range(1,10):
value = int(input("Score: "))
lists_dict[f"list_{i}"].append(value)
print(dict(lists_dict))
输出:
{'list_1': [1], 'list_2': [2], 'list_3': [3], 'list_4': [4], 'list_5': [5], 'list_6': [6], 'list_7': [7], 'list_8': [8], 'list_9': [9]}
我不确定这是您真正想要的,但是下面的代码可以做到:
length = 9
lst = [[] for i in range(length)]
for i in range(length):
value = int(input("Score: "))
lst[i].append(value)
print(lst)
基本上你不需要9个独立的列表。你想要一个嵌套列表。然后你可以用相应的索引调用顶部列表中的每个列表。
输出可能如下所示:
[[1], [2], [3], [4], [5], [2], [3], [1], [3]]