Home > Software design >  Find a value of a list in list and write a comment like duplicated python
Find a value of a list in list and write a comment like duplicated python

Time:12-26

list = [[2, 3, 4], [6, 7, 4], [10, 11, 12], [14, 15, 16], [18, 19, 12]]

I wont give a variable to code it will check the lists fourth value and if its duplicated in another list code will append a "found" string

list = [[2, 3, 4, "found"], [6, 7, 4, "found"], [10, 11, 12, "found"], [14, 15, 16], [18, 19, 12, "found"]]

I tried a lot but couldn't find any solutions.

listm = [[1, 2, 3, 4], [5, 6, 7, 4], [9, 10, 11, 12], [13, 14, 15, 16]]

c = 4

for i, alt_list in enumerate(listm):
  if c in alt_list:
   listm[i].append("found")

print(listm)

CodePudding user response:

Use an auxiliary dict to count occurrences of the last value of inner lists:

lst = [[2, 3, 4], [6, 7, 4], [10, 11, 12], [14, 15, 16], [18, 19, 12]]
counts = {}
for sub_l in lst:
    counts[sub_l[-1]] = 1 if sub_l[-1] not in counts else sub_l[-1]   1
lst = [l   ['found'] if counts[l[-1]] > 1 else l for l in lst]

print(lst)

[[2, 3, 4, 'found'], [6, 7, 4, 'found'], [10, 11, 12, 'found'], [14, 15, 16], [18, 19, 12, 'found']]

CodePudding user response:

Here is a counter-based approach:

from collections import Counter
lists = [[2, 3, 4], [6, 7, 4], [10, 11, 12], [14, 15, 16], [18, 19, 12]]
final_counts = Counter(sublist[-1] for sublist in lists)
for sublist in lists:
    if final_counts[sublist[-1]] > 1:
        sublist.append("found")
print(lists)

Output:

[[2, 3, 4, 'found'], [6, 7, 4, 'found'], [10, 11, 12, 'found'], [14, 15, 16], [18, 19, 12, 'found']]
  • Related