i have list of strings
lst = ["/foo/dir/c-.*.txt","/foo/dir2/d-.*.svc","/foo/dir3/es-.*.info"]
and i have prefix string :
/root
is there any pythonic way to add the prefix string to each element in the list
so the end result will look like this:
lst = ["/root/foo/dir/c-.*.txt","/root/foo/dir2/d-.*.svc","/root/foo/dir3/es-.*.info"]
if it can be done without iterating and creating new list ...
used:
List Comprehensions
List comprehensions provide a concise way to create lists. Common
applications are to make new lists where each element is the result of
some operations applied to each member of another sequence or
iterable, or to create a subsequence of those elements that satisfy a
certain condition.
F=Strings
F-strings provide a way to embed expressions inside string literals,
using a minimal syntax. It should be noted that an f-string is really
an expression evaluated at run time, not a constant value. In Python
source code, an f-string is a literal string, prefixed with 'f', which
contains expressions inside braces. The expressions are replaced with
their values.
lst = ["/foo/dir/c-.*.txt","/foo/dir2/d-.*.svc","/foo/dir3/es-.*.info"]
prefix = '/root'
lst =[ f'{prefix}{path}' for path in lst]
print(lst)
I am not sure of pythonic, but this will be also on possible way
list(map(lambda x: '/root' + x, lst))
Here there is comparison between list comp and map List comprehension vs map
Also thanks to #chris-rands learnt one more way without lambda
list(map('/root'.__add__, lst))
Use list comprehensions and string concatenation:
lst = ["/foo/dir/c-.*.txt","/foo/dir2/d-.*.svc","/foo/dir3/es-.*.info"]
print(['/root' + p for p in lst])
# ['/root/foo/dir/c-.*.txt', '/root/foo/dir2/d-.*.svc', '/root/foo/dir3/es-.*.info']
Just simply write:
lst = ["/foo/dir/c-.*.txt","/foo/dir2/d-.*.svc","/foo/dir3/es-.*.info"]
prefix="/root"
res = [prefix + x for x in lst]
print(res)
A simple list comprehension -
lst = ["/foo/dir/c-.*.txt","/foo/dir2/d-.*.svc","/foo/dir3/es-.*.info"]
prefix = '/root'
print([prefix + string for string in lst]) # You can give it a variable if you want
Related
Suppose I have a list of lists say
A = [[1,1,1,1],[2,2,2,2]]
and I want to create two strings from that to be
'1111'
'2222'
How would we do this in python?
Maybe list comprehension:
>>> A = [[1,1,1,1],[2,2,2,2]]
>>> l=[''.join(map(str,i)) for i in A]
>>> l
['1111', '2222']
>>>
Now you've got it.
This is pretty easily done using join and a list comprehension.
A = [[1,1,1,1],[2,2,2,2]]
a_strings = [''.join(map(str, sub_list)) for sublist in A]
See, join() takes a list of strings and makes a string concatenating all the substrings and the list comprehension I used just loops through them all. Above I combined the 2 together.
On a second thought
map() is actually deemed more efficient (when not using lambda.. etc) and for SOME more readable. I'll just add an approach using map instead of a comprehension.
a_strings = map(''.join(), map(str, A))
This first takes the inner map and makes all the ints > strs then joins all the strs together for every sub-list.
Hopefully this makes things a bit more chewable for ya, each method is close to equivalent such that for this case you could consider them style choices.
I have this:
name_list = [x for x in list]
if not name_list:
name_list = "n/a"
I want to make it in one line.
I want this:
name_list = ["n/a" if not x else x.text for x in list]
The problem I'm having if that I don't know what to put in the first x of the above code.
How do I check if the list is empty and make the value "n/a" in one line?
In the first code snippet, if the list is empty you assign a string to it. Not a list. Hence you can't do it with list comprehension, as the latter always returns a list.
You can use other Python builtin feature to achieve that:
name_list = [x.text for x in list] or "n\a"
It will evaluate the first expression first, and if its Falsey (None, False, 0) it will use the other expression - n\a.
You're mistaken here. You don't want a list comprehension. You use list comprehensions when you need to build new lists. That's not what you want to do here. You want to assign a certain value to name_list depending on a condition.
This can be done using Python's or operator. The or operator is short-circuited, and returns the first 'truthy' value it evaluates:
name_list = [x for x in list] or "n\a"
However, I would recommended being careful using the above code, as it can be confusing for people who aren't familiar with it. Depending on your case, it might be better to be more explicit and break the above code into two steps:
tmp = [x for x in list]
name_list = tmp if tmp else "n\a"
You can simply use or to do that like:
name_list = [x for x in a_list] or "n/a"
or is a short-circuit operator, so it only evaluates the second argument if the first one is false.
I want to check if strings in a list of strings contain a certain substring. If they do I want to save that list item to a new list:
list = ["Maurice is smart","Maurice is dumb","pie","carrots"]
I have tried using the following code:
new_list = [s for s in list if 'Maurice' in list]
but this just replicates the list if one of its items is 'Maurice'.
So I was wondering if, maybe, there was a way to solve this by using the following syntax:
if "Maurice" in list:
# Code that saves all list items containing the substring "Maurice" to a new list
Result should then be:
new_list = ["Maurice is smart", "Maurice is dumb"]
If been looking for a way to do this but I can not find anything.
You could do this:
list = ["Maurice is smart","Maurice is dumb","pie","carrots"]
new_list = [x for x in list if "Maurice" in x]
print(new_list)
Output:
['Maurice is smart', 'Maurice is dumb']
You could use Python's builtin filter:
data = ["Maurice is smart", "Maurice is dumb", "pie", "carrots"]
res = filter(lambda s: 'Maurice' in s, data)
print(res)
Output:
['Maurice is smart', 'Maurice is dumb']
The first argument is a predicate function (a simple lambda here) which must evaluate to True for the element of the iterable to be considered as a match.
filter is useful whenever an iterable must be filtered based on a predicate.
Also, a little extra, imagine now this data to be filtered:
data = ["Maurice is smart","Maurice is dumb","pie","carrots", "maurice in bikini"]
res = filter(lambda s: 'maurice' in s.lower(), list)
print(res)
Ouput:
['Maurice is smart', 'Maurice is dumb', 'maurice in bikini']
You can use a list comprehension.
Also, make sure not to use the built in list as variable name.
my_list = ["Maurice is smart", "Maurice is dumb", "pie", "carrots"]
[e for e in my_list if 'Maurice' in e]
I currently have a list that looks like the following:
list = ['325 153\n', '509 387\n', '419 397\n']
I am wondering how could i access these strings individually so i could use it in a function such as
for (x, y) in list:
where x is the first number of the string and y is the second number (separated by the space)
Is a good way to do this to turn the string into tuples somehow? I have tried using the 'split' function as i believe it is not valid for a list.
>>> a_list = ['325 153\n', '509 387\n', '419 397\n']
>>> [ i.split() for i in a_list ]
[['325', '153'], ['509', '387'], ['419', '397']]
You can iterate one the elements of the list:
for elem in list:
a, b = elem.split()[0], elem.split()[1]
a and b will be the elements and you can process them just as you wish.
[tuple(x.split()) for x in list]
this will return you a list of tuples
There is the split() method for string. Before using it you should use strip() to get rid of the training \n. At the end you can put both into a list comprehension:
for x, y in [item.strip().split(" ", 1) for item in lst]:
Note that I replace list with lst. list is a built-in type and should not be used as variable name.
I have a list of strings, and calling a function on each string which returns a string. The thing I want is to update the string in the list. How can I do that?
for i in list:
func(i)
The function func() returns a string. i want to update the list with this string. How can it be done?
If you need to update your list in place (not create a new list to replace it), you'll need to get indexes that corresponds to each item you get from your loop. The easiest way to do that is to use the built-in enumerate function:
for index, item in enumerate(lst):
lst[index] = func(item)
You can reconstruct the list with list comprehension like this
list_of_strings = [func(str_obj) for str_obj in list_of_strings]
Or, you can use the builtin map function like this
list_of_strings = map(func, list_of_strings)
Note : If you are using Python 3.x, then you need to convert the map object to a list, explicitly, like this
list_of_strings = list(map(func, list_of_strings))
Note 1: You don't have to worry about the old list and its memory. When you make the variable list_of_strings refer a new list by assigning to it, the reference count of the old list reduces by 1. And when the reference count drops to 0, it will be automatically garbage collected.
First, don't call your lists list (that's the built-in list constructor).
The most Pythonic way of doing what you want is a list comprehension:
lst = [func(i) for i in lst]
or you can create a new list:
lst2 = []
for i in lst:
lst2.append(func(i))
and you can even mutate the list in place
for n, i in enumerate(lst):
lst[n] = func(i)
Note: most programmers will be confused by calling the list item i in the loop above since i is normally used as a loop index counter, I'm just using it here for consistency.
You should get used to the first version though, it's much easier to understand when you come back to the code six months from now.
Later you might also want to use a generator...
g = (func(i) for i in lst)
lst = list(g)
You can use map() to do that.
map(func, list)