Home > database >  get half of all repeating elements in a list
get half of all repeating elements in a list

Time:01-23

my goal is to create a list with half of the individual items repeating in the list below i have given an example. In this list, except for the first element, each marked element is repeated 2n times, therefore all elements are even and divisible by 2. I can't create a list comprehension that divides by 2 the number of times each element is repeated. For example the element: [0, 255, 0] is repeated 6 times in the list; I expect in my new list to be repeated only 3 times.

list = [[255, 255, 255], [255, 0, 0], [255, 0, 0], [0, 255, 0], [0, 255, 0], [0, 255, 0], [0, 255, 0], [0, 255, 0], [0, 255, 0]]

list I expect = [[255, 255, 255], [255, 0, 0], [0, 255, 0], [0, 255, 0], [0, 255, 0]]

CodePudding user response:

You can use answer from shubham koli than create a new list as follow

list = [
  [255, 255, 255],
  [255, 0, 0], [255, 0, 0],
  [0, 255, 0], [0, 255, 0], [0, 255, 0], [0, 255, 0], [0, 255, 0], [0, 255, 0]
]


temp_list = []
for i in list:
    if i not in temp_list:
        temp_list.append(i)

result_list = []
for i in range(0, len(temp_list)):
  if i == 0:
    result_list.append(temp_list[i])
  else:
    n = list.count(temp_list[i])
    for j in range(n // 2):
      result_list.append(temp_list[i])

print(result_list)

which produces

[[255, 255, 255], [255, 0, 0], [0, 255, 0], [0, 255, 0], [0, 255, 0]]

as requested. Number of repreated items is store in n and is obtained using .count() from a list. Later n // 2 will give half of its value in integer.

CodePudding user response:

  result_list = []

for i in list:

    if i not in result_list:

        result_list.append(i)

print(result_list)

result list = [[255, 255, 255], [255, 0, 0], [0, 255, 0]]

  • Related