繁体   English   中英

从包含数字和字母的列表中对数字进行排序和推送到字典

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM