![](/img/trans.png)
[英]Convert list of tuple with string and list to the list of lists. [('str', [0, 0])...] to [['str', 0, 0]...]
[英]Convert the str to list of tuple
我將列表 1 中 AB 化合物中 A 和 B 的氧化態稱為('CaFe'、'BaSi'、'SeOs'、'BaGeO'、'CdCe'):
dfA = pd.read_csv("oxi_state.csv",index_col=0, header =0)
A1 = []
A2 = []
final = []
for i in range(len(list1)):
A1 = dfA['OS'][list1[i][0]]
A2 = dfA['OS'][list1[i][1]]
A = (A1, A2)
final.append(A)
final
當我從 DataFrame 調用數據時。 數據格式如下:
[('2', '2,3,4'),
('2', '4'),
('-2,4,6', '4,5,6,7'),
('2', '2,4'),
('2', '3,4')]
現在我想轉換為以下形式:
[([2], [2, 3, 4]), ([2], [4]), ([-2,4,6], [4,5,6,7]), ([2], [2,4]), ([2], [3,4])]
用於后期處理。
提前致謝
您可能必須遍歷所有項目。 使用
list('2,3,4')
將返回
['2',',','3',',','4']
然后,您可以通過並刪除逗號並將 str 轉換為 int
使用 split 方法和,
作為分隔符。
A1 = list(int(x) for x in dfA['OS'][list1[i][0]].split(","))
A2 = list(int(x) for x in dfA['OS'][list1[i][1]].split(","))
這是一個蠻力解決方案:
a = [('2', '2,3,4'),
('2', '4'),
('-2,4,6', '4,5,6,7'),
('2', '2,4'),
('2', '3,4')]
fin = []
for i in range(len(a)):
tup = []
for j in a[i]:
tmp = []
for v in j.split(','):
tmp.append(int(v))
tup.append(tmp)
fin.append(tuple(tup))
目前尚不清楚如何創建元組列表。 但是,根據當時顯示的示例:-
lot = [('2', '2,3,4'),
('2', '4'),
('-2,4,6', '4,5,6,7'),
('2', '2,4'),
('2', '3,4')]
for i, e in enumerate(lot):
lot[i] = [list(map(int, e_.split(','))) for e_ in e]
print(lot)
輸出:
[[[2], [2, 3, 4]], [[2], [4]], [[-2, 4, 6], [4, 5, 6, 7]], [[2], [2, 4]], [[2], [3, 4]]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.