2017-08-07 14 views
0

我有這樣的代碼:要怎樣才能與輸入[名單] .append()函數[PYTHON 3]

def add(whatlist): 
    inf = True 
    while inf == True and str(whatlist) in lists: 
     addtol = input('What do you want to add to list {0}? Type in STOP_ to end this process.: '.format(whatlist)) 
     if addtol.upper() != 'STOP_': 
      whatlist.append(addtol) 
     else: 
      inf = False 

當我輸入一個列表,解釋說:

'str' object has no attribute 'append' 

我怎麼能這樣做input()不會使我的輸入字符串?

+0

要麼你whatlist對象是字符串或者你需要用'addtol = STR輸入轉換爲字符串(輸入())' –

+4

可以告訴你,你叫'add'函數的代碼?那麼如何定義'lists'變量? – jdehesa

+3

你能提一下'whatlist'和'lists'的值嗎? – voidpro

回答

0

看來你似乎在這裏做了一些錯誤的事情。首先,whatList似乎是一個字符串而不是列表。所以你可能想先將它轉換成列表。一旦你確定你的whatList應該開始附加值。此外,global lists正在做什麼還有一些含糊之處。你可能也想解決這個問題。此外,一旦你得到輸入,你可以簡單地使用str將它轉換成字符串。

0

使用ast.literal_eval()使您的字符串列表。 eval()也可以工作,但並不安全。

>>> import ast 
>>> a = '[1,2,3,4]' 
>>> ast.literal_eval(a) 
[1, 2, 3, 4] 
>>> type(ast.literal_eval(a)) 
<class 'list'>