制作唯一号码列表

时间:2017-11-18 01:59:22

标签: python-3.x

我正在尝试列出唯一数字,但输出错误。

我想从每个行有两个数字的文件中获取每个唯一编号: 朋友= ['4 6','4 7','4 8','5 9','6 8','7 8','100 112','112 114','78 44']

答案: user = ['4','6','7','8','44','78','100','112','114']

但是我的以下代码输出user = ['0','1','2','4','5','6','7','8','9']而不是

我不确定如何让我的代码识别文件中的两位和三位数字,基本上这是我的问题

user=[]
for row in friends:
    for column in row:
            if column not in user and column.isdigit():
                user.append(column)

    user.sort()
print(user)

*我不允许使用词典,集,双端,平分模块

2 个答案:

答案 0 :(得分:1)

这样的事情:

friends=['4 6', '4 7', '4 8', '5 9', '6 8', '7 8', '100 112', '112 114', '78 44']

def get_numbers(mylist):
    nums = []                            # create a new list
    for i in mylist:                     # for each pair in the friends list
        nums.append(map(int, i.split())) # split each pair
                                         # convert them to integers
                                         # and append them to the new list
    return nums                          # return the new list

numbers = get_numbers(friends)           # call the function with the old list

然后你可以这样做:

print(numbers)   
[[4, 6], [4, 7], [4, 8], [5, 9], [6, 8], [7, 8], [100, 112], [112, 114], [78, 44]]

这应该有助于您入门。如果您遇到困难,请发表评论,我们可以对其进行更新。

答案 1 :(得分:1)

@pmnshift,我想我明白了!谢谢:))

def get_numbers(mylist):
    nums = [] 
    for i in mylist:                     
        nums.append(i.split())
        for i in range(len(nums)):
            for j in range(len(nums[0])):
                nums[i][j]= int(nums[i][j])
    return nums 

print(get_numbers(mylist))