2013-10-09 32 views
0

我正在嘗試製作一個程序,您可以選擇說中位數的選項,接下來我可以讓它請求您放入列表並說(「例如:10,40,30」),然後讓它把每個項目放在「,」之前,並將它附加到一個列表中,然後使其取出「,」。任何想法我可以做到這一點?列表中的Python Medians

這就是我的一切,到目前爲止

option5=(["1. Median", "2. Average", "3. Mean", "4. Mode"]) 
for items in option5: 
    print (items) 
    print ("") 
choice5=input("Choose another option: ") 
while choice5 not in ("1234"): 
    choice5=input("Choose another option: ") 
print("") 
if choice5 == "1": 
    print("Please put your list of numbers like the example below.") 
    print("Ex: 10,20,30") 
    print("") 
    median=input("List: ") 
+0

有一個看看'Counter' [收藏](http://docs.python.org/2/library/collections.html#collections.Counter) – danodonovan

回答

0

我想這是你想要什麼:median_list = median.split(",")

Here是字符串方法拆分的文檔。

我假設的輸入映射到輸出,像這樣:

1,2,3,4,5 - >["1", "2", "3", "4", "5"]

另一種方式,你可以做到這一點,這將是更加靈活,趕上像那些在您的評論輸入不正確使用ast.literal_eval(不要使用常規的eval,因爲它是不安全的)。

例子:

from ast import literal_eval 

try: 
    median_list = list(literal_eval(median)) 
except SyntaxError: 
    print("Invalid data was entered!") 
+0

感謝的人: )你知道我如何驗證它是以這種方式列出的嗎?例如,如果他們輸入「50 70 40 30」而不輸入「,」會比不行,所以我可以做一段時間的陳述來驗證他們是否以某種方式進行了驗證?我會做一些像中位數不在「,」:? – user2812028

+0

你可以嘗試做類似的事情,但我的編輯提供了一個更一般的答案。 – rlms

+0

感謝人:)但唯一的問題是,它說int對象是不可迭代的。有任何想法嗎?我認爲問題是它說除了SyntaxError,但如果這是一個TypeError? – user2812028