2017-11-25 248 views
1

只需在Python 3中學習,即可進行函數構建。我有一組函數可以接受來自用戶的多個元素並輸出唯一的元素。我想知道是否可以改進程序外觀,因爲如果有大量的輸入,它們會連成一個,一個接一個,一個接一個,一個接一個。理想情況下,每次用戶點擊輸入時,輸入行都會將元素和同一行重置爲下一個值。是否可以將輸入查詢保留爲1行(Python 3)

這是我有:

userlist = [] 
uniquelist = [] 

def make_list(list): #function to assign only unique list values 
    for u in userlist: 
     if u not in uniquelist: #only append element if it already appears 
      uniquelist.append(u) 
     else: 
      pass 
    print("The unique elements in the list you provided are:", uniquelist) 


def get_list(): #get list elements from user 
    i = 0 
    while 1: 
     i += 1 #start loop in get values from user 
     value = input("Please input some things: ") 
     if value == "": #exit inputs if user just presses enter 
      break 
     userlist.append(value) #add each input to the list 
    make_list(userlist) 

get_list() 

輸出(在Jupyter筆記本)增加了一個請輸入一些事情:行對每個元素的用戶輸入。 50路輸入,50路;看起來馬虎。我無法找到讓函數多次使用單行的方法。

+1

只是省略提示。你可以使用'iter'函數來替換'while'循環來獲取iter中的值(input,「」):userlist.append(value)',或者簡單地'userlist = list(iter(input,「」) )' – chepner

回答

0

您只需要使用map函數在一行中輸入數據,然後拆分每個數據,然後對它進行類型轉換以形成一個map對象,然後將其傳遞給list函數,該函數將返回變量中的列表這個:

var = list(map(int,input().split())) 
+0

它是Python 3:'raw_input'不存在,'map'創建一個迭代器而不是返回一個列表(當然不是一個數組)。 – chepner

+0

對不起,我沒有看到它被要求爲python3,我糾正它,所以現在它在python 3.x工作 – EX0MAK3R

+0

也許我沒有解釋(問)正確。用戶輸入內容並按下回車鍵。然後給他們另一個提示。按空格鍵輸入循環。我希望找到一種方法讓Python不要再呈現新行 - 而是每次都提供相同的行。 – Idleness

0

你想在每次輸入後清除控制檯中的文本嗎?然後,你可以在Unix系統上使用的Windows os.system('CLS')os.system('clear')

import os 

os.system('CLS') 
user_input = '' 
while user_input != 'quit': 
    user_input = input('Input something:') 
    os.system('CLS') # Clear the console. 
    # On Unix systems you have to use 'clear' instead of 'CLS'. 
    # os.system('clear') 

另外,我想你可以使用curses

相關問題