簡體   English   中英

將列表列表作為 python 中的輸入

[英]Take list of list as input in python

我需要輸入嚴格格式為[[a,b], [c,d], ... ]的輸入,即包含多個列表的列表。 所有內部列表將包含兩個 integer 項目。

例子:

a = [[0, 4], [1, 2], [5, 7], [6, 7], [6, 9], [8, 10]]

問題是當我將它作為輸入傳遞時,它被轉換為字符串,然后我使用這個程序來獲得所需的 output 但我無法使其正常工作。

def l2l(li):
    li = li.split(',', ' ')
    out= []
    for i in li:
        try:
            int(i)
            out.append(i)
        except ValueError:
            pass
    print(out)
    out = list([out[i], out[i+1]] for i in range(0,len(out)-1,2))

    return out

輸入:

a = [[0, 4], [1, 2], [5, 7], [6, 7], [6, 9], [8, 10]]

Output:

[['0', '4'], ['1', '2'], ['5', '7'], ['6', '7'], ['6', '9'], ['8', '1']]

使用 Python 模塊ast將其轉換為文字。

import ast 

a = "[[0, 4], [1, 2], [5, 7], [6, 7], [6, 9], [8, 10]]"

lol = ast.literal_eval(a)

print("({}){}".format(type(lol), lol))

OUTPUT:

(<class 'list'>)[[0, 4], [1, 2], [5, 7], [6, 7], [6, 9], [8, 10]]

使用python內置的eval function:

def l2l(li):
    li = eval(li)
    out= []
    for i in li:
        try:
            out.append(i)
        except ValueError:
            pass
    print(out)
    out = list([out[i], out[i+1]] for i in range(0,len(out)-1,2))

    return out
a = '[[0, 4], [1, 2], [5, 7], [6, 7], [6, 9], [8, 10]]'
l2l(a)

出去:

[[0, 4], [1, 2], [5, 7], [6, 7], [6, 9], [8, 10]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM