我正在嘗試找到一種從用戶那里獲取輸入的方法,即數字和單詞串列。然后我想只列印該串列中的數字。我不知道如何將它們分開,然后只列印出數字。我認為答案可能是通過將串列中的數字專案匯出到字典然后列印所述字典,但我不知道該怎么做。這是我已經擁有的代碼:
string1=input("Please input a set of positive numbers and words separated by a space: ")
string2=string1.split(" ")
string3=[string2]
dicts={}
for i in string3:
if isinstance(i, int):
dicts[i]=string3[i]
print(dicts)
uj5u.com熱心網友回復:
您只需要將單詞拆分成一個串列,然后根據每個單詞中的字符是否都是數字來列印串列中的單詞(使用str.isdigit):
string1 = input("Please input a set of positive numbers and words separated by a space: ")
# split into words
words = string1.split(' ')
# filter words and print
for word in words:
if word.isdigit():
print(word)
對于 的輸入abd 13 453 dsf a31 5b 42 ax12yz,這將列印:
13
453
42
或者,您可以過濾單詞串列(例如使用串列理解)并列印:
numbers = [word for word in words if word.isdigit()]
print(numbers)
上述樣本資料的輸出為:
['13', '453', '42']
uj5u.com熱心網友回復:
這是@Nick 的答案的一個細微變化,它使用串列理解,將輸入分成一個只包含數字的串列。
string1 = input("Please input a set of positive numbers and words separated by a space: ")
numbers = [x for x in string1.split(" ") if x.isdigit()]
print(numbers)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/504394.html
標籤:Python python-3.x
下一篇:python中的特殊陣列
