Reputation: 21
This is as much as I know how to do, not sure if I'm doing it correctly.
L = [4, 10, 4, 2, 9, 5, 4 ]
n = len(L)
element = ()
if element in L:
print(element)
print("number occurs in list at the following position, if element not in list")
print("this number does not occur in the list")
How do I go about getting elements that appear more than once, to print as
4 occurs in L at the following positions: [0, 2, 6]
Upvotes: 0
Views: 183
Reputation: 142146
The compulsory defaultdict
post:
from collections import defaultdict
el = [4, 10, 4, 2, 9, 5, 4 ]
dd = defaultdict(list)
for idx, val in enumerate(el):
dd[val].append(idx)
for key, val in dd.iteritems():
print '{} occurs in el at the following positions {}'.format(key, val)
#9 occurs in el at the following positions [4]
#10 occurs in el at the following positions [1]
#4 occurs in el at the following positions [0, 2, 6]
#2 occurs in el at the following positions [3]
#5 occurs in el at the following positions [5]
Then dd
can just be used a normal dict... dd[4]
or dd.get(99, "didn't appear")
Upvotes: 2
Reputation: 213233
You can use Counter
to count distinct element in list, then use list comprehension to find the index of each element: -
>>> l = [4, 10, 4, 2, 9, 5, 4 ]
>>> from collections import Counter
>>> count = Counter(l)
>>> count
Counter({4: 3, 9: 1, 10: 1, 2: 1, 5: 1})
>>> lNew = [[(i,x) for i,x in enumerate(l) if x == cnt] for cnt in count]
>>>
>>> lNew[0]
[(4, 9)]
>>> lNew[1]
[(1, 10)]
>>> lNew[2]
[(0, 4), (2, 4), (6, 4)]
>>>
In fact you don't need Counter
here. You can just get off with a Set
Create a Set of the list with the factory function : - set(l)
and then you can do the same with it..
Upvotes: 0
Reputation: 375475
def print_repeated_elements_positions(L):
for e in set(L): # only cover distinct elements
if L.count(e) > 1: #only those which appear more than once
print(e, "occurs at", [i for i, e2 in enumerate(L) if e2 == e])
L = [4, 10, 4, 2, 9, 5, 4]
print_repeated_elements_positions(L)
# prints: 4 occurs at [0, 2, 6]
Upvotes: 0
Reputation: 336148
You could use a list comprehension:
>>> L = [4, 10, 4, 2, 9, 5, 4]
>>> [i for i,x in enumerate(L) if x==4]
[0, 2, 6]
enumerate(L)
gives you an iterator over L
that yields a tuple (index, value)
for each element of L
. So what I'm doing here is take each index (i
) if the value (x
) equals 4
, and construct a list from them. No need to look at the length of the list.
Upvotes: 1