[英]Sorting and pushing numbers from a list that contains both numbers and letters to a dictionary
我正在嘗試找到一種從用戶那里獲取輸入的方法,即數字和單詞列表。 然后我想只打印該列表中的數字。 我不知道如何將它們分開,然后只打印出數字。 我認為答案可能是通過將列表中的數字項目導出到字典然后打印所述字典,但我不知道該怎么做。 這是我已經擁有的代碼:
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)
您只需要將單詞拆分為一個列表,然后根據每個單詞中的字符是否全為數字(使用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)
上述示例數據的 Output 將是:
['13', '453', '42']
這是@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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.