[英]Convert list of strings into tuple of integers
我需要將 2 個項目的字符串(用逗號分隔)轉換為整數。 還需要將列表列表切換為元組的元組。
從:
[['0,0'], ['0,1'], ['1,-1'], ['1,0']]
至:
((0,0), (0,1), (1,-1), (1,0))
我怎樣才能做到這一點?
謝謝。
您可以將 map 和具有列表理解的元組混合使用:
x = [['0,0'], ['0,1'], ['1,-1'], ['1,0']]
x = tuple([tuple(map(int, elt[0].split(','))) for elt in x])
print(x)
Output:
((0, 0), (0, 1), (1, -1), (1, 0))
說明: map
用於將元素轉換為int
的split
是內部列表的元素。 tuple
用於根據需要將類型轉換為tuple
。
您可以使用標准的“累加器模式”:
# Initialize an accumulator
outer_tuple = tuple()
for inner_list in outer_list:
a, b = inner_list[0].split(",")
a, b = int(a), int(b)
outer_tuple += ((a, b),)
首先, inner_list[0]
給出內部列表中的字符串,例如: "0,1"
。 接下來, .split(",")
將該字符串拆分為逗號字符,從而生成一個字符串列表: ["0", "1"]
。 然后, a, b =...
將列表“解包”到變量a
和b
中。 最后,我們將a
和b
轉換為int
並將其作為元組的元組添加到outer_tuple
(我們的累加器)。
我們需要做((a, b),)
的原因是因為當你添加兩個元組時,你實際上只是在做一個聯合,或者換句話說,你從兩個元組中獲取元素並創建一個新元組包含所有元素:
>>> x = (1, 2)
>>> y = (3, 4)
>>> x + y
(1, 2, 3, 4)
但這不是我們想要的。 我們想要一個元組的元組。 觀察會發生什么:
>>> x += y
>>> x
(1, 2, 3, 4)
>>> x += ((5, 6),)
>>> x
(1, 2, 3, 4, (5, 6))
希望這可以幫助:
First, we will make a list for the output, then we will iterate through every element in the input list and then make a tupled version of it, the tupled version would be made by spliting the string by the comma and then use the map function獲得一個具有 int 類型而不是字符串的元組版本。 然后 append 到 output 列表。 最后將 output 列表轉換為元組。
inputGiven = [['0,0'], ['0,1'], ['1,-1'], ['1,0']]
outputGivenInList = []
for i in inputGiven:
tupledVersion = tuple(map(int, i[0].split(",")))
outputGivenInList.append(tupledVersion)
finalOutput = tuple(outputGivenInList)
print(finalOutput)
一個簡單的方法:
>>> tmp = tuple(eval(str(li).replace('\'', '')))
>>> ans = (tuple(tmp[i]) for i in range(4))
>>> ans
<generator object <genexpr> at 0x000001754697D8C8>
>>> tuple(ans)
((0, 0), (0, 1), (1, -1), (1, 0))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.