How do I remove duplicated elements from a python array? - list

What I just want to achieve is to be able to get a list with elemnts that aren't repeating
<current state>
results = ["Anna","Michael","Anna","Juliet","Juliet", "Anna"]
<expectation>
results=["Anna","Michael", "Juliet"]

The following will remove duplicates.
results = ["Anna","Michael","Anna","Juliet","Juliet", "Anna"]
results = list(dict.fromkeys(results))
print(results)
Output:
['Anna', 'Michael', 'Juliet']
See https://www.w3schools.com/python/python_howto_remove_duplicates.asp for more information.

You can conver the list to a set, which has no duplicates by definition.
results = set(["Anna","Michael","Anna","Juliet","Juliet", "Anna"])
If you need the type of the result to be a list, you can simply convert it back:
results = list(set(["Anna","Michael","Anna","Juliet","Juliet", "Anna"]))

Related

How to show which values of one list are in other list?

Having 2 lists, I want check which values of List1 are in List2. I'm trying as below but I get error
List1 = {3,2,8,7,5}
List2 = {1,3,4,2,6,7,9}
= List.Transform(List1, each Text.Contains(List2, _))
Expression.Error: We cannot convert a value of type List to type Text.
Details:
Value=[List]
Type=[Type]
My expected output would be 3,2,7.
How can I do this?
See List.Intersect Documentation
Intersect = List.Intersect({List1,List2})
#horseyride has probably the best answer but using your original logic, you could also write the intersection like this:
List.Select(List1, each List.Contains(List2, _))
This uses Select instead of Transform since you are trying to select/filter instead of changing the elements and uses the appropriate List type instead of Text for the Contains part.

Looping through a list (with sublists) and assign the matching IDs to the same key and all of the corresponding values from that sublist?

I'm quite new in python coding and I canĀ“t solve the following problem:
I have a list with trackingpoints for different animals(ID,date,time,lat,lon) given in strings:
aList = [[id,date,time,lat,lon],
[id2,date,time,lat,lon],
[...]]
The txt file is very big and the IDs(a unique animal) is occuring multiple times:
i.e:
aList = [['25','20-05-13','15:16:17','34.89932','24.09421'],
['24','20-05-13','15:16:18','35.89932','23.09421],
['25','20-05-13','15:18:15','34.89932','24.13421'],
[...]]
What I'm trying to do is order the ID's in dictionaries so each unique ID will be the key and all the dates, times, latitudes and longitudes will be the values. Then I would like to write each individual ID to a new txt file so all the values for a specific ID are in one txt file. The output should look like this:
{'25':['20-05-13','15:16:17','34.89932','24.09421'],
['20-05-13','15:18:15','34.89932','24.13421'],
[...],
'24':['20-05-13','15:16:18','35.89932','23.09421'],
[...]
}
I have tried the following (and a lot of other solutions which didn't work):
items = {}
for line in aList:
key,value = lines[0],lines[1:]
items[key] = value
Which results in a key with the last value in the list forthat particular key :
{'25':['20-05-13','15:18:15','34.89932','24.13421'],
'24':['20-05-13','15:16:18','35.89932','23.09421']}
How can I loop through my list and assign the same IDs to the same key and all the corresponding values?
Is there any simple solution to this? Other "easier to implement" solutions are welcome!
I hope it makes sense :)
Try adding all the lists that match to the same ID as list of lists:
aList = [['25','20-05-13','15:16:17','34.89932','24.09421'],
['24','20-05-13','15:16:18','35.89932','23.09421'],
['25','20-05-13','15:18:15','34.89932','24.13421'],
]
items = {}
for line in aList:
key,value = line[0],line[1:]
if key in items:
items[key].append(value)
else:
items[key] = [value]
print items
OUTPUT:
{'24': [['20-05-13', '15:16:18', '35.89932', '23.09421']], '25': [['20-05-13', '15:16:17', '34.89932', '24.09421'], ['20-05-13', '15:18:15', '34.89932', '24.13421']]}

Removing a word from a list which appears one after the other

Lets say i have a list of words as shown below,
A=['ab','bc','cd','de','de','ef','bc']
I tried to use sets as seen below,
def remove_similar_words(self,sent):
original_set = set()
result = []
for item in sent:
if item not in original_set:
original_set.add(item)
result.append(item)
return result
sent is list A.
The result of the above method would be
result=['ab','bc','cd','de','ef']
But, i need the result to be,
needed_result=['ab','bc','cd','de','ef','bc']
Question : How can i change my code to cater the requirement of producing the list needed_result?
Also i would like to avoid sets since i need to preserve the order.
def remove_similar_words(sent):
last = ""
result = []
for item in sent:
if item != last:
last=item
result.append(item)
return result
A=['ab','bc','cd','de','de','ef','bc']
print (", ".join(remove_similar_words(A)))
It would seem you just need to check against the prior value in your iterator, not build a complete original_set.

To append an element into a list without generating any other elements

Trying to append an element into an empty list as follows, while appending it also adds a character 'u' like [u'slice'] into the empty list while adding an element into the list, however expected is ['slice']
Code as follows:
type = slice # value for type
value = []
value.append(type)
Output:
value = [u'slice']
Requesting people for help to get output as ['slice'].
For some reason the output is in Unicode, hence the u. Try re-encoding it to ascii
by using .encode("ascii"). Sorry I don't know why it's doing that though.

Python Get Elements of List if Matched

Given the following list:
colors=['#c85200','#5f9ed1','lightgrey','#ffbc79','#006ba4','dimgray','#ff800e','#a2c8ec'
,'grey','salmon','cyan','silver']
And this list:
Hospital=['a','b','c','d']
After I get the number of colors based on the length of the list - 'Hospital':
num_hosp=len(Hospital)
colrs=colors[:num_hosp]
colrs
['#c85200', '#5f9ed1', 'lightgrey', '#ffbc79']
...and zip the lists together:
hcolrs=zip(Hospitals,colrs)
Next, I'd like to be able to select 1 or more colors from hcolrs if given a list of one or more hospitals from 'Hospitals'.
Like this:
newHosps=['a','c'] #input
newColrs=['#c85200','lightgrey'] #output
Thanks in advance!
Pass the result of zip to the dict constructor to make lookup simple/fast:
# Don't need to slice colors; zip stops when shortest iterable exhausted
hosp_to_color = dict(zip(Hospitals, colors))
then use it:
newHosps = ['a','c']
newColrs = [hosp_to_color[h] for h in newHosps]