I have a huge list of lists, this is a section of it:
[['cusA', 'zupT', 'rcnA', 'cusA', 'zupT', 'zupT']]
I did the following operation on the entire list of lists:
[list(x) for x in set(tuple(x) for x in my_list)]
because I would like to have unique information in the sublists. This returned the following:
[['c', 'u', 's', 'A'], ['r', 'c', 'n', 'A'], ['z', 'u', 'p', 'T']]
Which is great, since it did become unique, but now I need them to be in their original from, without being broken up character-by-character.
Is there any way to re-join them inside the sublists?
Instead of list(x)
, use ''.join(x)
.
But you can just put the strings themselves in a set instead of calling tuple: list(set(my_list))
.
as you already mentioned: you can join
the strings:
print(''.join(['c', 'u', 's', 'A'])) # cusA
for your whole list you could do this:
lst = [['c', 'u', 's', 'A'], ['r', 'c', 'n', 'A'], ['z', 'u', 'p', 'T']]
str_lst = [''.join(item) for item in lst]
print(str_lst) # ['cusA', 'rcnA', 'zupT']
note that there is no point in creating a list of single characters; a string itself behaves exactly like a list of characters (an immutable one, though); so you could directoy do this:
print(set(['cusA', 'zupT', 'rcnA', 'cusA', 'zupT', 'zupT']))
# {'zupT', 'cusA', 'rcnA'}
# if you need a list again instead of a set:
print(list(set(['cusA', 'zupT', 'rcnA', 'cusA', 'zupT', 'zupT'])))
# ['zupT', 'cusA', 'rcnA']
that will not preserve the order though...
If the ordering of the contents of the inner lists does not matter, you can turn them into a set, which is a an un-ordered collection of unique elements, and then turn that set back into a list:
result = [list(set(li)) for li in my_list]
Prints:
[['cusA', 'rcnA', 'zupT']]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.