Вы можете сделать это, например, sort
ing на основе index
в оригинальном list
,
>>> x
[7, 31, 31, 61, 61, 79, 29, 79, 29, 103, 37, 103, 37, 47, 47, 53, 53, 89, 5, 89, 5, 13, 13, 83, 83, 101, 53, 101, 17, 53, 11, 17, 11, 59, 17, 59, 17, 41, 41, 79, 79, 97, 3, 97, 3, 41, 19, 41, 19, 53, 53, 67, 29, 67, 29, 73, 23, 73, 23, 43, 43, 71]
# the `sorted` function takes a `key` function, that one can use to manipulate how the sort should be based on
# In this case, you could use `index` of the `element` in the `list` `x`,
# So, while the sort goes through each element, it check against the index in the original list, which is `x, thus it aligns each item based on the `index`.
>>> sorted(x, key=x.index) # note that you have more than a pair, so :)
[7, 31, 31, 61, 61, 79, 79, 79, 79, 29, 29, 29, 29, 103, 103, 37, 37, 47, 47, 53, 53, 53, 53, 53, 53, 89, 89, 5, 5, 13, 13, 83, 83, 101, 101, 17, 17, 17, 17, 11, 11, 59, 59, 41, 41, 41, 41, 97, 97, 3, 3, 19, 19, 67, 67, 73, 73, 23, 23, 43, 43, 71]
Если вы действительно заботитесь о pair
, тогда
>>> data = []
>>> for k in sorted(x, key=x.index): # `using direct x.index instead of useless lambda(i previously used) in this case, as @Austin suggested
... if data.count(k) < 2: # add the element until it reaches count 2, which is `pair`, which is what you asked for
... data.append(k)
...
>>> data
[7, 31, 31, 61, 61, 79, 79, 29, 29, 103, 103, 37, 37, 47, 47, 53, 53, 89, 89, 5, 5, 13, 13, 83, 83, 101, 101, 17, 17, 11, 11, 59, 59, 41, 41, 97, 97, 3, 3, 19, 19, 67, 67, 73, 73, 23, 23, 43, 43, 71]
Причина:
list.index
будет return
первое совпадение index
.Скажем, у вас есть list
, x = [1,2,1,3]
и x.index(1)
всегда будет return
0
.Таким образом, будет sorted
иначе, если использовать list.index
в качестве ключевой функции для sort
ing