I have a list of like below, some of them are prefixed with "abc_" and some of them are not.
What would be the effective way to prefix the ones that do not have the prefix?
(Basically, I need all of them to have the prefix "abc_")
my_list = ['abc_apple','abc_orange','cherry','abc_berry','banana']
Required output:
my_list = ['abc_apple','abc_orange','abc_cherry','abc_berry','abc_banana']
Is it Possible to do it using list comprehension?
Don't name lists with a Python Keyword. list is a keyword in Python. You can use list comprehension to do it using .startswith():
list1 = ['abc_apple','abc_orange','cherry','abc_berry','banana']
list1 = ['abc_'+i if not i.startswith('abc_') else i for i in list1]
print(list1)
Output:
['abc_apple', 'abc_orange', 'abc_cherry', 'abc_berry', 'abc_banana']
Just following if/else in a list comprehension you could do something like this:
my_list = ['abc_apple','abc_orange','cherry','abc_berry','banana']
my_list = [f"abc_{word}" if not word.startswith("abc_") else word for word in my_list]
print(my_list)
Output:
['abc_apple', 'abc_orange', 'abc_cherry', 'abc_berry', 'abc_banana']
list = ['abc_apple','abc_orange','cherry','abc_berry','banana']
for i in range(len(list)):
if 'abc_' in list[i]:
pass
else:
list[i] = 'abc_' + list[i]
list
output:
['abc_apple', 'abc_orange', 'abc_cherry', 'abc_berry', 'abc_banana']
OR
list = ['abc_apple','abc_orange','cherry','abc_berry','banana']
for i in range(len(list)):
if 'abc_' not in list[i]:
list[i] = 'abc_' + list[i]
list
OR Better answer
list = ['abc_apple','abc_orange','cherry','abc_berry','banana']
for i in range(len(list)):
if list[i].startswith('abc_'):
pass
else:
list[i] = 'abc_' + list[i]
list
Try method map to make an iterator that computes the function using arguments from each of the iterables.
>>> lst = ['abc_apple','abc_orange','cherry','abc_berry','banana']
>>> result = list(map(lambda x:x if x.startswith('abc_') else 'abc_'+x, lst))
>>>
>>> result
['abc_apple', 'abc_orange', 'abc_cherry', 'abc_berry', 'abc_banana']
Related
This question already has answers here:
How to add an integer to each element in a list?
(12 answers)
Closed last month.
I would like to get such a result [2,4,5,6,7], how can do that? Now i get this: [7]
list1 = [1,3,4,5,6]
for i in range(len(list1)):
l = []
# list1[i] = list1[i] + 1
s = list1[i] + 1
l.append(s)
print(l)
you can use list comprehension
list1 = [1,3,4,5,6]
newlist = [x+1 for x in list1]
print(newlist)
If you want to use a loop, you need to put l = [] ahead of it - otherwise you're reintializing it as an empty list at each loop iteration,
list1 = [1,3,4,5,6]
l = []
for el in list1:
l.append(el + 1)
print(l)
Notice that this code directly loops through elements of list1. This is a preferred way for lists and any other iterables. I recommend you use it whenever practical/possible.
As an alternative to list comprehensions and loops, you can also use a map with a lambda,
list1 = [1,3,4,5,6]
new_list = list(map(lambda x: x+1, list1))
print(new_list)
Note, however, that in most situations, including this one, list comprehension is a better choice. For reasons and details, look up this post.
This will work:
list1 = [1,3,4,5,6]
for i in range(len(list1)):
list1[i]+=1
print(list1)
I have a list that contains duplicates, some are exactly the same while others have just a prefix at the beginning.
For example the following entries refer to the same entry:
'user01', 'aa-user01', 'xyz-user01'
I succeeded to remove the entries that are exactly the same but not the ones with a prefix:
list = ['user01','user01', 'aa-user01','user02','user02', 'user03', 'xyz-user02']
list2 = []
for i in range(0, len(list)):
if list[i] not in list2:
list2.append(list[i])
print(list2)
I get this:
['user01', 'aa-user01', 'user02', 'user03', 'xyz-user02']
The resulat that i want:
['user01', 'user02', 'user03']
The simplest fix would only consider the token after the "-":
for x in list:
user = x.rsplit("-", 1)[-1]
if user not in list2:
list2.append(user)
Note: you should not shadow built-in names like list. Also, contains-checks are expensive for lists, so if you have lots of data, you should consider using a set or dict.
s = set(x.rsplit("-", 1)[-1] for x in lst)
Docs:
str.rsplit
for i in range(0, len(list)):
if list[i][list[i].find("user"):] not in list2:
list2.append(list[i])
list1 = ['user01','user01', 'aa-user01','user02','user02', 'user03', 'xyz-user02']
list2 = []
for i in range(0, len(list1)):
if list1[i] not in list2:
list2.append(list1[i])
list2 = list(dict.fromkeys(list2))
print(list2)
print(list2)
One way to do this would be to first remove the prefix using a list comprehension;
Remove prefix
list = ['user01','user01', 'aa-user01','user02','user02', 'user03', 'xyz-user02']
list = [i.split('-', 1)[-1] for i in l]
list2 = []
for i in range(0, len(list)):
if list[i] not in list2:
list2.append(list[i])
print(list2)
You can go with a short list comprehension, including:
lower() -> Ignore case typing (remove if not needed)
split() -> Removes the prefix
set() -> Removes duplicates
Your result will be set([x.lower().split('-', 1)[-1] for x in test_list]) while test_list is your list.
my_list = ['user01','user01', 'aa-user01','user02','user02', 'user03', 'xyz-user02']
new_list = [j.split('-')[1] if len(j.split('-'))==2 else j for j in my_list]
['user01', 'user01', 'user01', 'user02', 'user02', 'user03', 'user02']#value of new_list
set(new_list)#output unique values
{'user01', 'user02', 'user03'}
I have the following two lists. If my_list ends with an extension from extensions, then it should be removed. I can't seem to find a solution that doesn't require too many lines of code.
Input:
my_list = ['abc_sum_def_sum', 'abc_sum_def_mean', 'abc_sum', 'abc_abc']
extensions = ['_sum', '_mean']
Output:
new_list = ['abc_sum_def', 'abc_sum_def', 'abc', 'abc_abc']
One-liner list comprehension:
new_list = [min(e[:(-len(ext) if e.endswith(ext) else len(e))] for ext in extensions) for e in my_list]
Result:
['abc_sum_def', 'abc_sum_def', 'abc', 'abc_abc']
Explanation:
What this does is basically loops over my_list, checks if its element e has either of the two extensions items at its end. If it does, it trims that extensions piece down. If it doesn't, leaves that element of my_list untouched. It basically first does this (without the min applied):
[[e[:(-len(ext) if e.endswith(ext) else len(e))] for ext in extensions] for e in my_list]
which produces:
[['abc_sum_def', 'abc_sum_def_sum'],
['abc_sum_def_mean', 'abc_sum_def'],
['abc', 'abc_sum'],
['abc_abc', 'abc_abc']]
and then applies min to collect the smaller item of each pair. That min corresponds to either the trimmed-down version of each element, or the untouched element itself.
To have a better pythonic approach, You can convert it into a list comprehension:
my_list = ['abc_sum_def_sum','abc_sum_def_mean','abc_sum','abc_abc']
extensions = ['_sum','_mean']
new_list =[]
for x in my_list:
for elem in extensions:
if x.endswith(elem):
y = x[:-len(elem)]
new_list.append(y)
This is one approach using Regex.
Ex:
import re
my_list = ['abc_sum_def_sum','abc_sum_def_mean','abc_sum','abc_abc']
extensions = ['_sum','_mean']
pattern = re.compile(r"(" + "|".join(extensions) + r")$")
print([pattern.sub("", i) for i in my_list])
Output:
['abc_sum_def', 'abc_sum_def', 'abc', 'abc_abc']
my_list = ['abc_sum_def_sum','abc_sum_def_mean','abc_sum','abc_abc']
extensions = ['_sum','_mean']
new_list =[]
for x in my_list:
if x.endswith(extensions[0]) or x.endswith(extensions[1]):
if x.endswith(extensions[0]):
y = x[:-len(extensions[0])]
new_list.append(y)
else:
y = x[:-len(extensions[1])]
new_list.append(y)
else:
new_list.append(x)
print(new_list)
output:
['abc_sum_def', 'abc_sum_def', 'abc', 'abc_abc']
A solution using lambdas:
my_list = ['abc_sum_def_sum','abc_sum_def_mean','abc_sum','abc_abc']
extensions = ['_sum','_mean']
def ext_cleaner(extensions, str_arg):
ext_found = [ext for ext in extensions if str_arg.endswith(ext)]
ret = str_arg[:-len(ext_found[0])] if ext_found else str_arg
return ret
list(map(lambda x: ext_cleaner(extensions, x), my_list))
I want to add a value to a list of lists.
For input of [[1,2],[2,3]]
I want output of [[2,3],[3,4]]
I can do it with loops:
list_of_lists = [[1,2],[2,3]]
output = []
for list in list_of_lists:
sub_output = []
for value in list:
sub_output.append(value+1)
output.append(sub_output)
print(output)
Can I do this with list comprehension?
If I do:
[value + 1 for list in list_of_lists for value in list]
It gives me [2,3,3,4]. Can I get it to keep the sublist format somehow?
Try...
[ [n + 1 for n in inner_list] for inner_list in list ]
Yeah, you need a nested comprehension:
[[item + 1 for item in list] for list in list_of_lists]
Another way would be to use map:
map(lambda l: map(lambda i: i + 1, l), list_of_lists)
You need to nest a comprehension into that comprehension. Unpack each sublist to make it easier.
[[a+1, b+1] for a,b in list_of_lists]
I am new to python and I'm wondering, how I would go about removing items from a list. Say I have the list:
a=[(102,12,0),(123,12,0),(124,12,1)]
I would like to remove the items that have a 0 at the end, so my list would end up like:
a = [(124,12,1)]
here:
a = [i for i in a if i[-1] != 0] #list comprehension (1 line) method.
"normal" way to do without list comprehension when the parent list is also destination list.
tmp = []
for i in a:
if i[-1] != 0:
tmp.append(i)
a = tmp
in action:
>>> a=[(102,12,0),(123,12,0),(124,12,1)]
>>> a = [i for i in a if i[-1] != 0]
>>> a
[(124, 12, 1)]
>>>
You can use list comprehensions
val[-1] would give you tuples with 0 at the end, assuming val is the variable used while iterating.
So, your code would be something like this:
a = [val for val in a if val[-1]]
Not as awesome as a one liner list comprehension but still do the trick :).
b = tuple
for tple in a:
b = b + tple
result = tuple
for val in set(b):
if val % 10 != 0:
result = result + (val,)