Python 字符串 2d 列表到混合整数/字符串列表



得到这个列表:

test_list = [['1', '350', 'apartment'], ['2', '300', 'house'], ['3', '300', 'flat'], ['4', '250', 'apartment']]

尝试获得混合列表,例如

test_list = [[1, 350, 'apartment'], [2, 300, 'house'], [3, 300, 'flat'], [4, 250, 'apartment']]

到目前为止,我的尝试:

res = [list(map(lambda ele : int(ele) if ele.isdigit()  
else ele, test_list)) for ele in test_list ] 

但似乎不起作用。

如果您已经知道每个子列表的位置是正确的,为什么要使用 map

res = [[int(x), int(y), z] for x, y, z in test_list] 

结果

[[1, 350, 'apartment'], [2, 300, 'house'], [3, 300, 'flat'], [4, 250, 'apartment']]    

甚至更好,因为这可能是字典,最终使用字典理解:

res = {int(i): {'price': int(p), 'name': n} for i, p, n in test_list}

结果

{1: {'price': 350, 'name': 'apartment'}, 2: {'price': 300, 'name': 'house'}, 3: {'price': 300, 'name': 'flat'}, 4: {'price': 250, 'name': 'apartment'}}

变量只有一个小问题。

在此修复中,test_list是整个列表,ele['1', '350', 'apartment']x是其中的单个字符串。

[list(map(lambda x: int(x) if x.isdigit() else x, ele)) for ele in test_list]

但最好使用列表理解而不是list(map(

[[int(x) if x.isdigit() else x for x in ele] for ele in test_list]

更好的是:字典列表或元组列表会更合适。列表通常是元素的集合,没有每个元素的特定角色。

[{'id': int(id), 'price': int(price), 'name': name} for id, price, name in test_list]
[(int(id), int(price), name) for id, price, name in test_list]

如果第三项(在我的示例中为名称(被随机称为"123",也会阻止您将它转换为整数。

试试这个:

test_list = [[int(ele) if ele.isdigit() else ele for ele in elem ] for elem in test_list]