0
replaced items problem
why when i try to replace the count item bigger than 1 just two items replaced and the last item not replaced.. thanks a = ['one' , 'one' , 'one' , 'two' , 'three'] i = 0 sec = [] for x in range(len(a)): if a.count(a[x]) > 1: a[x] = 'replaced' i = i + 1 print(a) ## out put : # ['replaced', 'replaced', 'one', 'two', 'three']
4 Answers
+ 2
The issue with your code is this:
First time the program goes through the loop, the count for 'one' is 3 and so it replaces the first occurrence of 'one' by 'replaced'.
The second time the count for 'one' is 2 and it replaces that one once again.
By the time it gets to the 3rd 'one' the count for 'one' is now 1 and thus nothing is replaced.
Take a look at the answer marked as best in the thread in the link bellow. I think it will help soleve the issue... They used enumerate. It might be an opportunity to learn something new as well. ;)
https://stackoverflow.com/questions/2582138/finding-and-replacing-elements-in-a-list-JUMP_LINK__&&__python__&&__JUMP_LINK
+ 2
Alternatively, you can turn the list into a String and take advantage of Strings replace method... This might be slower though depending on the time complexity of those methods
https://code.sololearn.com/czVR0A98zb5t/?ref=app
+ 1
I assume desired output is replaced on every number that has already occured.
maybe this helps::
if x in dupl variable:
replace
elif x in a:
replace
add x to found dupl variable
+ 1
لان عدد مرات ظهور عنصر ال( x) المطلوب بالنسبه للشرط الموضوع هو مرتين
لكن لو
a[x] >=1
هيستبدل ٣ مرات وكذلك باقي العناصر
وال i ليس لها افاده
وكذلك ال sec