0

所以我已经让程序工作了,到目前为止我的问题是我的解决方案要求输出看起来像这样[44, 76, 34, 98, 1, 99]但是['1', '2', '3', '5', '6', '7']如果我的输入是44 76 44 34 98 34 1 44 99 1 1 1

尝试将最终解决方案转换为 int 然后再转换回字符串不起作用,我仍然得到引号。

顺便说一句,代码的要点是从给定输入中删除重复项并将其打印在列表中

def eliminateDuplicates(lst): 
    newlist = []
    for number in lst:
        if number not in newlist:
            newlist.append(number)
    return newlist

def main():
    numbers =(input("Enter numbers separated by space: "))
    x = ((numbers.split()))
    print("The distinct numbers are: ", (eliminateDuplicates(x))) 

main()
4

6 回答 6

1

在第一行中,我们将输入存储在 d 中。在第二行中,我们将 d 转换为 set() 并返回到 list()。在第三行中,我们将 map() d 映射到整数。

d = raw_input("Enter Numbers: ").split()
d = list(set(d))
d = map(int, d)
print d
于 2015-11-21T13:23:15.680 回答
0

尝试这个:

print("The distinct numbers are: ", map(int, eliminateDuplicates(x)))
于 2013-11-01T05:00:03.913 回答
0

如果参数lst应该是 a list,为什么不输入一个列表作为输入?(而不是用空格分隔的数字)。然后你可以省略这些split东西:

def eliminateDuplicates(lst): 
    newlist = []
    for number in lst:
        if number not in newlist:
            newlist.append(number)
    return newlist

def main():
    numbers =(input("Enter numbers as a list: "))
    print("The distinct numbers are: ", (eliminateDuplicates(numbers))) 
main()
于 2013-11-01T05:03:14.383 回答
0

希望这可以帮助:

from collections import OrderedDict
def eliminateDuplicates(lst): 
    newlist = [int(x) for x in lst]
    newlist = list(OrderedDict.fromkeys(newlist))
    return newlist

def main():
    numbers =(input("Enter numbers separated by space: "))
    x = ((numbers.split()))
    print("The distinct numbers are: ", (eliminateDuplicates(x))) 
main()
于 2013-11-01T06:59:23.223 回答
0

打印数字时在数字周围加上引号的原因是因为您正在打印 a list,这会将列表隐式转换为字符串(使用str)。该list类型的__str__方法使用它repr的每个列表项。字符串的repr将引号括起来。

这是有充分理由的。repr应该是对象的计算机友好表示。eval如果可能,它应该在ed时创建对象的副本。如果列表或字符串在打印时表现不同,则类似的列表["foo", "bar, baz", "quux"]将具有模棱两可的repr.

将输入值转换为整数(正如其他答案所建议的那样)是一种解决方案,但对于此任务来说不是必需的。您的重复数据删除功能适用于字符串列表。如果输出格式是唯一的问题,您可以从字符串列表str.formatstr.join创建所需格式的输出字符串,而不是直接打印列表。例如:

print("The distinct numbers are: [{}]".format(", ".join(eliminateDuplicates(x)))
于 2013-11-01T07:25:07.540 回答
0

只需替换这行代码。

x =[ int(num) for num in numbers.split(' ') if len(num)>0 ]

一切都会好起来的。
更改此行后,您的整个代码将如下所示

def eliminateDuplicates(lst): 
newlist = []
for number in lst:
    if number not in newlist:
        newlist.append(number)
return newlist

def main():
    numbers =(input("Enter numbers separated by space: "))
    x =[ int(num) for num in numbers.split(' ') if len(num)>0 ]
    print("The distinct numbers are: ", (eliminateDuplicates(x))) 

main()

输出将是

Enter numbers separated by space: 44 76 44 34 98 34 1 44 99 1 1 1
The distinct numbers are:  [44, 76, 34, 98, 1, 99]

在 python 中读取空格分隔的输入时,它们被视为字符串,因此您需要将它们转换为整数。字符串可以通过多种方式转换为整数,如下所示
使用列表推导

numbers = [ int(num) for num in input().split(' ') if len(num)>0 ]

使用过滤器和映射功能

numbers = list(map(int,filter(lambda x : len(x)>0,input().split(' '))))
于 2021-11-10T09:25:36.690 回答