How to use trim strings in a list comprehension? [duplicate] - python

This question already has answers here:
Strip a list in Python [closed]
(3 answers)
Closed 5 months ago.
keywords = ['a', 'b', '(c)']
keywords = [keyword for keyword in keywords if "(" in keyword and ")" in keyword]
I want the output to be:
keywords = ['a', 'b', 'c']
How to modify the list comprehension to get the result without using a loop?

Try strip:
>>> keywords = ['a', 'b', '(c)']
>>> [kw.strip('()') for kw in keywords]
['a', 'b', 'c']
>>>

strip works. Alternate solution using replace() as well:
>>> keywords = ['a', 'b', '(c)']
>>> [kw.replace('(','').replace(')','') for kw in keywords]
['a', 'b', 'c']

A list comprehensions in Python is a type of loop
Without using a loop:
keywords = ['a', 'b', '(c)']
keywords = list(map(lambda keyword: keyword.strip('()'), keywords))

Related

I want to change a tuple into string without joining it in python. How could I do that? [duplicate]

This question already has answers here:
Convert a list to a string without 'join'
(5 answers)
Closed 2 years ago.
For Example:
I want to change
t=('a', 'b', 'c')
to
s='a', 'b', 'c'
t = ('a', 'b', 'c')
s = 'a','b', 'c'
print(s==t)
# output True
if you want s = 'a,b,c' then you can do it by joining which you do not want to do. Also, it's useless to write 'a','b','c' as string, however you can do that by using commented code. Please consider writing s = a,b,c
s = ''
for i in t:
s += str(',') + i # s += str(',') + str("'") + i + str("'")
s = s[1:]
If you want a list that contains the letters:
t_modified=list(t)
output
['a', 'b', 'c']
t=('a', 'b', 'c')
print(list(t))
['a', 'b', 'c']
",".join(list(t))

How to dynamically unpack a list as you create? [duplicate]

This question already has answers here:
Unpack list into middle of a tuple
(3 answers)
Closed 4 years ago.
How would I create a list element from function call?
Not sure if this is possible, but I've tried to create a list element from a function when i create the list as i'm not sure of the elements up until runtime
So I have tried this:
>>>> def make_list_element():
return 'd, e'
If i then try to create a list and call the function at the same time :
>>>> a = ['a', 'b', 'c', make_list_element().split(", ")]
And I get:
>>> a
>>> ['a', 'b', 'c', ['d', 'e']]
How could I achieve this:
>>> a
>>> ['a', 'b', 'c', 'd', 'e']
Preferably in the same statement as I create the list.
Many thanks
In Python3, you can simply unpack the returned list like so:
a = ['a', 'b', 'c', *make_list_element().split(", ") ]
If you're on Python2, you will have to concatenate or extend the list:
a = ['a', 'b', 'c'] + make_list_element().split(", ")
or
a = ['a', 'b', 'c']
a.extend(make_list_element().split(", "))

How to get only lowercase strings from a list using list comprehension

The question asked:
Use list comprehensions to generate a list with only the lowercase letters in my_list. Print the result list.
['a', 'A', 'b', 'B', 'c', 'C', 'd', 'D']
My code:
my_list = ['a', 'A', 'b', 'B', 'c', 'C', 'd', 'D']
hi = ([ char for char in range(len(my_list)) if char%2 == 0])
print(hi)
I tried it out, but got integers as answers and not the strings I wanted.
Note: several answers here assume that what you want is to select the values in the list that are lowercase. This answer assumes that that was an example and that the thing you're trying to do is to select the values in the list that occur at every other list index. (This seems to me to be the correct interpretation, because that's what the implementation in the question appears to be trying to do.) I'm not sure who misunderstood the question here, but since the question can be interpreted multiple ways, I think the question is probably at fault here. Until the question is clarified, I think it should be placed on hold.
The simplest and fastest way to do this is with a slice:
print(my_list[::2]) # Slice the whole list, with step=2
To replicate the logic you're describing, where you want to take the values with indexes that are modulo 2, then you need to generate both the indexes and the values for your list in the comprehension, and use one for the filtering and the other for the result:
hi = [ch for ix, ch in enumerate(my_list) if ix % 2 == 0]
Python strings have islower method. Also, you can directly iterate over the list, no need to check its length or the parity of the indexes.
my_list = ['a', 'A', 'b', 'B', 'c', 'C', 'd', 'D']
hi = [char for char in my_list if char.islower()]
print(hi)
# ['a', 'b', 'c', d']
Your list comprehension:
[char for char in range(len(my_list)) if char%2 == 0]
Will produce integers instead of characters. This is because range(len(my_list)) gives you indices. You instead need to get the characters.
This can be done using enumerate():
[char for i, char in enumerate(my_list) if i % 2 == 0]
Or a less pythonic approach, using just indexing my_list:
[my_list[i] for i in range(len(my_list)) if i % 2 == 0]
You can also just filter out the lowercase letters with str.islower():
[char for char in my_list if char.islower()]
Which avoids having to use indices altogether.
You can use list comprehension as following where you iterate over your individual elements and check if it is a lower case using .islower()
my_list = ['a', 'A', 'b', 'B', 'c', 'C', 'd', 'D']
lower = [i for i in my_list if i.islower()]
# ['a', 'b', 'c', 'd']
my_list = ['a', 'A', 'b', 'B', 'c', 'C', 'd', 'D']
res = [ char for char in my_list if ord(char)>=97]
using islower() function
l = ['a', 'A', 'b', 'B', 'c', 'C', 'd', 'D']
result = [el for el in l if el.islower()]
To add a range(len(my_list)) that create the following range(0, 8)
and char, in this case, is an integer and you create a list of integers.
To generate a list with only the lowercase letters use 'islower' method
hi = ([ char for char in my_list if char.islower()])

I'd like to make the python's list to ['a','a','b',b','c','c'] from ['a','b','c'] [duplicate]

This question already has answers here:
Duplicate each member in a list [duplicate]
(12 answers)
Closed 5 years ago.
I'd like to make the python's list to ['a','a','b',b','c','c'] from ['a','b','c'].
Anyboday know to do this?
Thank you !
For something that more or less says “I want to repeat each element twice”, there’s the nested list comprehension with range:
>>> l = ['a', 'b', 'c']
>>> [x for x in l for _ in range(2)]
['a', 'a', 'b', 'b', 'c', 'c']
You can make it a tiny bit shorter with a list multiplication if you find that more readable and won’t need to extend 2 to a large number and convert the list comprehension to a generator expression:
>>> l = ['a', 'b', 'c']
>>> [y for x in l for y in [x, x]]
If you’re a fan of Haskell, where l >>= replicate 2 would work, you can imitate that:
import itertools
from functools import partial
from operator import mul
def flat_map(iterable, f):
return itertools.chain.from_iterable(map(f, iterable))
l = ['a', 'b', 'c']
flat_map(l, partial(mul, 2))
You could always create a new list:
for x in oldList:
newList.append(x)
newList.append(x)
Note that this will create a new list rather than modifying the old one!
source = ['a','b','c']
result = [el for el in source for _ in (1, 2)]
print(result)
gives you
['a', 'a', 'b', 'b', 'c', 'c']

Create all sequences from the first item within a list

Say I have a list, ['a', 'b', 'c', 'd']. Are there any built-ins or methods in Python to easily create all contiguous sublists (i.e. sub-sequences) starting from the first item?:
['a']
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']
in Python?
Note that I am excluding lists/sequences such as ['a' ,'c'], ['a', 'd'], ['b'], ['c'] or ['d']
To match your example output (prefixes), then you can just use:
prefixes = [your_list[:end] for end in xrange(1, len(your_list) + 1)]
You can do this with a simple list comprehension:
>>> l = ['a', 'b', 'c', 'd']
>>>
>>> [l[:i+1] for i in range(len(l))]
[['a'], ['a', 'b'], ['a', 'b', 'c'], ['a', 'b', 'c', 'd']]
See also: range()
If you're using Python 2.x, use xrange() instead.
A little more Pythonic than using (x)range (with the benefit of being the same solution for either Python 2 or Python 3):
lst = list('abcde')
prefixes = [ lst[:i+1] for i,_ in enumerate(lst) ]
If you decided that the empty list should be a valid (zero-length) prefix, a small hack will include it:
# Include 0 as an slice index and still get the full list as a prefix
prefixes = [ lst[:i] for i,_ in enumerate(lst + [None]) ]
Just as an alternative:
def prefixes(seq):
result = []
for item in seq:
result.append(item)
yield result[:]
for x in prefixes(['a', 'b', 'c', 'd']):
print(x)

Categories

Resources