通过 int 转换存储在嵌套列表中的用户输入 - Python
User input to store in nested lists with int conversion - Python
我需要将用户输入存储在 A = [[a, b, c], [d, e, f]]...
形式的嵌套列表中,依此类推,基于用户需要的嵌套列表的数量。 a, b, c, ...
是整数;所以我也需要将用户输入从 str
转换为 int
。这是我到目前为止得到的:
number_of_nested_lists = int(input())
i = 0
data = []
while(i < number_of_nested_lists):
user_input = int(input())
data.append(user_input)
i = i + 1
用户一次输入三个值点,形式为:
1 2 3
4 5 6
7 8 9
等等。我无法将输入数据从 str 转换为 int,作为 ValueError ValueError: invalid literal for int() with base 10: '1 2 3'
结果 data
应该是 data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
。 Python 的新手,仍在努力弄清楚列表的概念。我试图在没有 numpy 的情况下做到这一点。谢谢。
你可以这样做:
data.append([int(x) for x in input().split()])
list = []
for i in range(x):
input = raw_input("Enter data point:")
temp_list = input.split(" ")
list.append(temp_list)
print list
您可以使用raw_input
,默认情况下输出为字符串。然后只需将输入字符串拆分为 temp_list
(列表对象)。
我需要将用户输入存储在 A = [[a, b, c], [d, e, f]]...
形式的嵌套列表中,依此类推,基于用户需要的嵌套列表的数量。 a, b, c, ...
是整数;所以我也需要将用户输入从 str
转换为 int
。这是我到目前为止得到的:
number_of_nested_lists = int(input())
i = 0
data = []
while(i < number_of_nested_lists):
user_input = int(input())
data.append(user_input)
i = i + 1
用户一次输入三个值点,形式为:
1 2 3
4 5 6
7 8 9
等等。我无法将输入数据从 str 转换为 int,作为 ValueError ValueError: invalid literal for int() with base 10: '1 2 3'
结果 data
应该是 data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
。 Python 的新手,仍在努力弄清楚列表的概念。我试图在没有 numpy 的情况下做到这一点。谢谢。
你可以这样做:
data.append([int(x) for x in input().split()])
list = []
for i in range(x):
input = raw_input("Enter data point:")
temp_list = input.split(" ")
list.append(temp_list)
print list
您可以使用raw_input
,默认情况下输出为字符串。然后只需将输入字符串拆分为 temp_list
(列表对象)。