簡體   English   中英

如何在 Python 中進行字符串輸入時限制列表打印?

[英]How to limit list printing while taking string input in Python?

我有下面的python代碼,您可以看到我將名稱作為用戶的輸入,如果它與名稱列表中存在的名稱匹配,則代碼中斷。 我目前的要求是,如果用戶鍵入數字(例如: 1,2 )或名稱(左,右)而不是列表中提到的,那么它應該提示他們錯誤“輸入不正確。請從下面的列表中輸入名稱”並打印列表行中的元素。 下面代碼的問題是它根據列表元素的長度打印元素列表。 例如。 如果我輸入 "Left","Right", "center" 作為輸入,那么我下面的代碼將打印輸出部分中顯示的輸出,而不是打印預期輸出中顯示的輸出。

我的問題是如何修復下面的代碼,以便當用戶鍵入以逗號分隔的錯誤名稱時,它應該打印一次列表元素。 我確定我可能會遺漏一些小東西,但不確定它是什么?

注意:我在代碼的輸入部分使用過濾器的原因是因為我想從用戶輸入生成的列表中刪除空元素。

在此先感謝您的時間!

代碼

names=['test','bob','rob']

def validate1(string_text):
    try:
        for x in string_text:
            if x not in names:
                print("Incorrect entry please enter names from below list")
                for y in names: print(y)
            else:
                return True        
    except ValueError:
        print("Incorrect entry. Please enter name in string format ONLY!")
        return False 

while True:
    name_with_deg=list(filter(None,input("Enter names separated by (,):").split(",")))
    if validate1(name_with_deg):
        break

輸出:

Enter names separated by (,):Left,Right,center
Incorrect entry please enter names from below list
test
bob
rob
Incorrect entry please enter names from below list
test
bob
rob
Incorrect entry please enter names from below list
test
bob
rob

預期輸出:

Enter names separated by (,):Left,Right,center
Incorrect entry please enter names from below list
test
bob
rob

for x in string_text:循環遍歷每個名​​稱,因此多個名稱/多個循環進行測試。 您想要的是在一次測試中測試所有名稱都在names中。 這是一種使用all和生成器表達式的方法:

names=['test','bob','rob']

def validate1(name_list):
    result = all(name in names for name in name_list)
    if not result:
        print('Incorrect entry please enter names from below list')
        for name in names:
            print(name)
    return result

while True:
    # list(filter(None,...)) didn't do anything...removed.
    # input() always returns a string, so the try/except wasn't needed either
    name_with_deg = input('Enter names separated by (,):').split(',')
    if validate1(name_with_deg):
        break

暫無
暫無

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

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