このようなコードを作りました。このコードはリストの中から1回しか出てこない数字を最終的に新たなリストとして出すコードです。このコード自体は動くのですが、最初に入力リストの順番が小さい順(1〜)に変わります。sort()が原因なのかなと思いつつ、sort()をなくしてこのコードをもう一度動かしたところ、入力したリストがそのまま何も変換されず出てきました。何が原因なのでしょうか?またどこが間違っているでしょうか?教えていただけると嬉しいです。
# Read a list of integers from input. # Each number is separated by a space. # Do not modify line 5. print("Enter a list of numbers separated by spaces:") list = [int(s) for s in input().split()] # the variable 'list' contains the list of numbers # this is to show you the list, you can delete this line. # your code goes here. list.sort() num = len(list) if list[0] != list[1]: print(list[0], end = ' ') for x in range(1, num-1): if (list[x] != list[x + 1] and list[x] != list[x - 1]): print(list[x], end = ' ') if list[num - 2] != list[num - 1]: print(list[num - 1], end = ' ')
Outputはこのような結果になりました。このOutputを反対にすればいいのですが、それではリストごとで違ってきてしまうので、どんなリストがきても順番に沿ってOutputが出てくるようにしたいです。
Enter a list of numbers separated by spaces: 4 3 5 2 5 1 3 5 1 2 4
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/05/12 14:56