如何在整数列表列表中分隔多位整数
How to seperate multi-digit integer in list of list of integers
我有这个输入:
12 13 23 31 34 41
从这里开始,我想要一个整数列表:
[[1, 2], [1, 3], [2, 3], [3, 1], [3, 4], [4, 1]]
到目前为止,这是我的代码
e1 = (input())
e1 = e1.split()
def nest_lists(lst):
return [[el] for el in lst]
edges = nest_lists(e1)
for i in range(len(edges)):
for x in range(len(edges[i])):
edges[i][x] = int(edges[i][x])
print(edges)
我目前的输出是:
[[12], [13], [23], [31], [34], [41]]
由于您使用的是 input
我假设您的实际输入是字符串 '12 13 23 31 34 41'
.
您可以结合使用 split
、list
和 map
以某种实用的方式完成此操作:
e1 = '12 13 23 31 34 41'
output = list(map(lambda x: list(map(int, list(x))), e1.split()))
print(output)
产出
[[1, 2], [1, 3], [2, 3], [3, 1], [3, 4], [4, 1]]
接受的答案非常好,但由于您用 list-comprehension
标记了问题,我想您可能也想看到这个:
text_in = '12 13 23 31 34 41'
text_out = [
[int(character) for character in word]
for word in text_in.split(" ")
]
print(text_out)
类似的结果是:
[[1, 2], [1, 3], [2, 3], [3, 1], [3, 4], [4, 1]]
我有这个输入:
12 13 23 31 34 41
从这里开始,我想要一个整数列表:
[[1, 2], [1, 3], [2, 3], [3, 1], [3, 4], [4, 1]]
到目前为止,这是我的代码
e1 = (input())
e1 = e1.split()
def nest_lists(lst):
return [[el] for el in lst]
edges = nest_lists(e1)
for i in range(len(edges)):
for x in range(len(edges[i])):
edges[i][x] = int(edges[i][x])
print(edges)
我目前的输出是:
[[12], [13], [23], [31], [34], [41]]
由于您使用的是 input
我假设您的实际输入是字符串 '12 13 23 31 34 41'
.
您可以结合使用 split
、list
和 map
以某种实用的方式完成此操作:
e1 = '12 13 23 31 34 41'
output = list(map(lambda x: list(map(int, list(x))), e1.split()))
print(output)
产出
[[1, 2], [1, 3], [2, 3], [3, 1], [3, 4], [4, 1]]
接受的答案非常好,但由于您用 list-comprehension
标记了问题,我想您可能也想看到这个:
text_in = '12 13 23 31 34 41'
text_out = [
[int(character) for character in word]
for word in text_in.split(" ")
]
print(text_out)
类似的结果是:
[[1, 2], [1, 3], [2, 3], [3, 1], [3, 4], [4, 1]]