如何在保持相同列表结构的同时转换类型

时间:2019-02-22 06:09:51

标签: python python-3.x

所以我在这里有此列表:

[['Afghanistan', '2.66171813', '7.460143566', '0.490880072', '52.33952713', '0.427010864', '-0.106340349', '0.261178523'], ['Albania', '4.639548302', '9.373718262', '0.637698293', '69.05165863', '0.74961102', '-0.035140377', '0.457737535'], ['Algeria', '5.248912334', '9.540244102', '0.806753874', '65.69918823', '0.436670482', '-0.194670126', ''], ['Argentina', '6.039330006', '9.843519211', '0.906699121', '67.53870392', '0.831966162', '-0.186299905', '0.305430293'], ['Armenia', '4.287736416', '9.034710884', '0.697924912', '65.12568665', '0.613697052', '-0.132166177', '0.246900991'], ['Australia', '7.25703764', '10.71182728', '0.949957848', '72.78334045', '0.910550177', '0.301693261', '0.45340696']]

我的目标是遍历列表列表,并将数字字符串值转换为整数。

我尝试过

for li in main_li:
    for element in li:
        if element == li[0]:
            continue
        else:
            element = int(element)

我的问题是如何在不使用数字作为字符串的情况下,将其恢复为与上面相同的列表格式。

6 个答案:

答案 0 :(得分:2)

您可以通过对代码进行一些小的更改来实现

for li in main_li:
for i in range(1,len(li)):
    try:
        li[i] = int(li[i])
    except ValueError:
        pass

答案 1 :(得分:1)

当您遍历列表值时,您不应(不是说不可能)更改列表值。您必须创建一个新列表。幸运的是,您只需对原始代码进行少量修改即可轻松完成此操作:

newlist = []
for li in main_li:
    newli = []
    for element in li:
        if element == li[0]:
            newli.append(element)
        else:
            try:
                newli.append(int(float(element)))
            except Exception as e:
                newli.append(0) # This is added because not everything in your list can be converted to int.
    newlist.append(newli)

newlist将成为您修改后的列表列表。

或者,您可以使用列表理解:

newlist = [[p[0]] + [int(float(x)) for x in p[1:]] for p in main_li]

请注意这是如何要求所有字符串正确格式化的。

答案 2 :(得分:1)

您的列表元素是浮动的,因此您只能将它们转换为浮动的:

import re
pattern = re.compile('[-+]?\d+(\.\d+)?') # a pattern for all number types
new_list = []
for nest in l:
    temp_list = []
    for val in nest:
        if bool(pattern.match(val)): #check if the element is a number
            temp_list.append(float(val))
            continue
        temp_list.append(val)
    new_list.append(temp_list)  
print(new_list)
[['Afghanistan', 2.66171813, 7.460143566, 0.490880072, 52.33952713, 0.427010864, -0.106340349, 0.261178523], ['Albania', 4.639548302, 9.373718262, 0.637698293, 69.05165863, 0.74961102, -0.035140377, 0.457737535], ['Algeria', 5.248912334, 9.540244102, 0.806753874, 65.69918823, 0.436670482, -0.194670126, ''], ['Argentina', 6.039330006, 9.843519211, 0.906699121, 67.53870392, 0.831966162, -0.186299905, 0.305430293], ['Armenia', 4.287736416, 9.034710884, 0.697924912, 65.12568665, 0.613697052, -0.132166177, 0.246900991], ['Australia', 7.25703764, 10.71182728, 0.949957848, 72.78334045, 0.910550177, 0.301693261, 0.45340696]]

答案 3 :(得分:0)

只需将可转换的元素转换为float并通过迭代列表索引在当前列表中对其进行更改:

for i in range(len(main_li)):
    for j in range(len(main_li[i])):
        try:
            main_li[i][j] = float(main_li[i][j])
        except ValueError:
            continue


li # [['Afghanistan', 2.66171813, 7.460143566, 0.490880072, 52.33952713, 0.427010864, -0.106340349, 0.261178523], ['Albania', 4.639548302, 9.373718262, 0.637698293, 69.05165863, 0.74961102, -0.035140377, 0.457737535], ['Algeria', 5.248912334, 9.540244102, 0.806753874, 65.69918823, 0.436670482, -0.194670126, ''], ['Argentina', 6.039330006, 9.843519211, 0.906699121, 67.53870392, 0.831966162, -0.186299905, 0.305430293], ['Armenia', 4.287736416, 9.034710884, 0.697924912, 65.12568665, 0.613697052, -0.132166177, 0.246900991], ['Australia', 7.25703764, 10.71182728, 0.949957848, 72.78334045, 0.910550177, 0.301693261, 0.45340696]]

答案 4 :(得分:0)

大多数答案都采用固定级别的嵌套(列表列表)。您可以(如果适用)使用以下代码,该代码使用递归处理更深层的嵌套列表(列表列表等)。

 <!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

    <!-- Apply your custom dialog theme here. -->
    <item name="android:dialogTheme">@style/CustomDialog</item>
    <item name="android:alertDialogTheme">@style/CustomDialog</item>
</style>

<style name="CustomDialog" parent="Theme.AppCompat.Light.Dialog">
    <item name="android:windowAnimationStyle">@style/CustomDialogAnimation</item>
</style>

<style name="CustomDialogAnimation">
    <item name="android:windowEnterAnimation">@android:anim/slide_in_left</item>
    <item name="android:windowExitAnimation">@android:anim/slide_out_right</item>
</style>

顺便说一句,check this SO answer看看Python认为是浮点数...

答案 5 :(得分:0)

您可以在listcomp中使用星号拆包:

l = [['A', '1.1', '1.2'], ['B', '2.1', '2.2']]

[[i, *map(float, j)] for i, *j in l]
# [['A', 1.1, 1.2], ['B', 2.1, 2.2]]