Multiple list comprehension actions in a single line - python

I am currently performing the following actions to make a list lowercase then remove the dots.
lowercase_list = [x.lower() for x in my_list]
lowercase_stripped_list = [x.replace('.', '') for x in lowercase_list]
is there a way to do this in a single line?
Thanks

Chain the method calls (str.lower returns a string, you can call another string method str.replace on the return value):
>>> my_list = ['Hello. World', 'Big.Big.World']
>>> [x.lower().replace('.', '') for x in my_list]
['hello world', 'bigbigworld']

Related

How to split a single value list to multiple values in same list

I did some workarounds but none of them worked so here I am with a question on how can we split a value from a list based on a keyword and update in the same list
here is my code,
result_list = ['48608541\ncsm_radar_main_dev-7319-userdevsigned\nLogd\nG2A0P3027145002X\nRadar\ncompleted 2022-10-25T10:43:01\nPASS: 12FAIL: 1SKIP: 1\n2:25:36']
what I want to remove '\n' and write something like this,
result_list = ['48608541', 'csm_radar_main_dev-7319-userdevsigned', 'Logd', 'G2A0P3027145002X', .....]
You need to split each of the string by \n which results in a list that you need to flatten. You can use list-comprehension:
>>> [x for item in result_list for x in item.split('\n') ]
# output:
['48608541', 'csm_radar_main_dev-7319-userdevsigned', 'Logd', 'G2A0P3027145002X', 'Radar', 'completed 2022-10-25T10:43:01', 'PASS: 12FAIL: 1SKIP: 1', '2:25:36']
this will split each element of your list at \n and update in same list
result_list = [item for i in result_list for item in i.split('\n') ]
Solution using regex (re):
import re
result_list = re.split('\n', result_list[0])
#output:
['48608541', 'csm_radar_main_dev-7319-userdevsigned', 'Logd', 'G2A0P3027145002X', 'Radar', 'completed 2022-10-25T10:43:01', 'PASS: 12FAIL: 1SKIP: 1', '2:25:36']
The split() method of the str object does this:
Return a list of the words in the string, using sep as the delimiter string.
>>> '1,2,3'.split(',')
['1', '2', '3']
so here we have the answer as follows:
string_object = "48608541\ncsm_radar_main_dev-7319-userdevsigned\nLogd\nG2A0P3027145002X\nRadar\ncompleted 2022-10-25T10:43:01\nPASS: 12FAIL: 1SKIP: 1\n2:25:36"
result_list = string_object.split(sep='\n')

Remove double quotes and special characters from string list python

I'm pretty new in python.
I have a list like this:
['SACOL1123', "('SA1123', 'AAW38003.1')"]
['SACOL1124', "('SA1124', 'AAW38004.1')"]
And I want to remove the extra double quotes and paranthesis, so it looks like this:
['SACOL1123', 'SA1123', 'AAW38003.1']
['SACOL1124', 'SA1124', 'AAW38004.1']
This is what I managed to do:
newList = [s.replace('"(', '') for s in list]
newList = [s.replace(')"', '') for s in newList]
But the output is exactly like the input list. How can I do it?
This is possible using ast.literal_eval. Your second element from list is string representation of a valid Python tuple which you can safely evaluate.
[[x[0]] + list(ast.literal_eval(x[1])) for x in lst]
Code:
import ast
lst = [['SACOL1123', "('SA1123', 'AAW38003.1')"],
['SACOL1124', "('SA1124', 'AAW38004.1')"]]
output = [[x[0]] + list(ast.literal_eval(x[1])) for x in lst]
# [['SACOL1123', 'SA1123', 'AAW38003.1'],
# ['SACOL1124', 'SA1124', 'AAW38004.1']]
This can be done by converting each item in the list to a string and then substituting the punctuation with empty string. Hope this helps:
import re
List = [['SACOL1123', "('SA1123', 'AAW38003.1')"],
['SACOL1124', "('SA1124', 'AAW38004.1')"]]
New_List = []
for Item in List:
New_List.append(re.sub('[\(\)\"\'\[\]\,]', '', str(Item)).split())
New_List
Output: [['SACOL1123', 'SA1123', 'AAW38003.1'],
['SACOL1124', 'SA1124', 'AAW38004.1']]

how to remove "\n" from a list of strings

I have a list that is read from a text file that outputs:
['/Users/myname/Documents/test1.txt\n', '/Users/myname/Documents/test2.txt\n', '/Users/myname/Documents/test3.txt\n']
I want to remove the \n from each element, but using .split() does not work on lists only strings (which is annoying as this is a list of strings).
How do I remove the \n from each element so I can get the following output:
['/Users/myname/Documents/test1.txt', '/Users/myname/Documents/test2.txt', '/Users/myname/Documents/test3.txt']
old_list = [x.strip() for x in old_list]
old_list refers to the list you want to remove the \n from.
Or if you want something more readable:
for x in range(len(old_list)):
old_list[x] = old_list[x].strip()
Does the same thing, without list comprehension.
strip() method takes out all the whitespaces, including \n.
But if you are not ok with the idea of removing whitespaces from start and end, you can do:
old_list = [x.replace("\n", "") for x in old_list]
or
for x in range(len(old_list)):
old_list[x] = old_list[x].replace("\n", "")
do a strip but keep in mind that the result is not modifying the original list, so you will need to reasign it if required:
a = ['/Users/myname/Documents/test1.txt\n', '/Users/myname/Documents/test2.txt\n', '/Users/myname/Documents/test3.txt\n']
a = [path.strip() for path in a]
print a
Give this code a try:
lst = ['/Users/myname/Documents/test1.txt\n', '/Users/myname/Documents/test2.txt\n', '/Users/myname/Documents/test3.txt\n']
for n, element in enumerate(lst):
element = element.replace('\n', '')
lst[n] = element
print(lst)
Use:
[i.strip() for i in lines]
in case you don't mind to lost the spaces and tabs at the beginning and at the end of the lines.
You can read the whole file and split lines using str.splitlines:
temp = file.read().splitlines()
if you still have problems go to this question where I got the answer from
How to read a file without newlines?
answered Sep 8 '12 at 11:57 Bakuriu
There are many ways to achieve your result.
Method 1: using split() method
l = ['/Users/myname/Documents/test1.txt\n', '/Users/myname/Documents/test2.txt\n', '/Users/myname/Documents/test3.txt\n']
result = [i.split('\n')[0] for i in l]
print(result) # ['/Users/myname/Documents/test1.txt', '/Users/myname/Documents/test2.txt', '/Users/myname/Documents/test3.txt']
Method 2: using strip() method that removes leading and trailing whitespace
l = ['/Users/myname/Documents/test1.txt\n', '/Users/myname/Documents/test2.txt\n', '/Users/myname/Documents/test3.txt\n']
result = [i.strip() for i in l]
print(result) # ['/Users/myname/Documents/test1.txt', '/Users/myname/Documents/test2.txt', '/Users/myname/Documents/test3.txt']
Method 3: using rstrip() method that removes trailing whitespace
l = ['/Users/myname/Documents/test1.txt\n', '/Users/myname/Documents/test2.txt\n', '/Users/myname/Documents/test3.txt\n']
result = [i.rstrip() for i in l]
print(result) # ['/Users/myname/Documents/test1.txt', '/Users/myname/Documents/test2.txt', '/Users/myname/Documents/test3.txt']
Method 4: using the method replace
l = ['/Users/myname/Documents/test1.txt\n', '/Users/myname/Documents/test2.txt\n', '/Users/myname/Documents/test3.txt\n']
result = [i.replace('\n', '') for i in l]
print(result) # ['/Users/myname/Documents/test1.txt', '/Users/myname/Documents/test2.txt', '/Users/myname/Documents/test3.txt']
Here is another way to do it with lambda:
cleannewline = lambda somelist : map(lambda element: element.strip(), somelist)
Then you can just call it as:
cleannewline(yourlist)

Extracting the first word from every value in a list

So I have a long list of column headers. All are strings, some are several words long. I've yet to find a way to write a function that extracts the first word from each value in the list and returns a list of just those singular words.
For example, this is what my list looks like:
['Customer ID', 'Email','Topwater -https:', 'Plastics - some uml']
And I want it to look like:
['Customer', 'Email', 'Topwater', 'Plastics']
I currently have this:
def first_word(cur_list):
my_list = []
for word in cur_list:
my_list.append(word.split(' ')[:1])
and it returns None when I run it on a list.
You can use list comprehension to return a list of the first index after splitting the strings by spaces.
my_list = [x.split()[0] for x in your_list]
To address "and it returns None when I run it on a list."
You didn't return my_list. Because it created a new list, didn't change the original list cur_list, the my_list is not returned.
To extract the first word from every value in a list
From #dfundako, you can simplify it to
my_list = [x.split()[0] for x in cur_list]
The final code would be
def first_word(cur_list):
my_list = [x.split()[0] for x in cur_list]
return my_list
Here is a demo. Please note that some punctuation may be left behind especially if it is right after the last letter of the name:
names = ["OMG FOO BAR", "A B C", "Python Strings", "Plastics: some uml"]
first_word(names) would be ['OMG', 'A', 'Python', 'Plastics:']
>>> l = ['Customer ID', 'Email','Topwater -https://karls.azureedge.net/media/catalog/product/cache/1/image/627x470/9df78eab33525d08d6e5fb8d27136e95/f/g/fgh55t502_web.jpg', 'Plastics - https://www.bass.co.za/1473-thickbox_default/berkley-powerbait-10-power-worm-black-blue-fleck.jpg']
>>> list(next(zip(*map(str.split, l))))
['Customer', 'Email', 'Topwater', 'Plastics']
[column.split(' ')[0] for column in my_list] should do the trick.
and if you want it in a function:
def first_word(my_list):
return [column.split(' ')[0] for column in my_list]
(?<=\d\d\d)\d* try using this in a loop to extract the words using regex

Put a symbol between every letter in a list of strings

How would I put ! after every character in a list
listOne = ["hello","world"]
How do I turn that into:
["h!e!l!l!o","w!o!r!l!d"]
Attempt:
def turn(List):
return [i for i in (list(lambda x: "%s!" % x,listOne))]
turn(listOne)
Returns:
['hello!',"world!"]
Is their another way to do this besides:
def turn(List):
x = ""
for word in words:
for letter in word:
x += "%s!" % letter
return x
turn(listOne)
I'm not a big fan of doing things like that however I do realize that may be more pythonic than what I'm trying to do which is make it as few lines as possible so. Is this possible?
You can easily achieve this with the str.join() method, and list comprehension:
>>> listOne = ['!'.join(i) for i in listOne]
>>> listOne
Output
['h!e!l!l!o', 'w!o!r!l!d']
Alternatively, as abarnert suggested, you can use the bulit-in map function.
>>> listOne = list(map('!'.join, listOne))
>>> listOne
['h!e!l!l!o', 'w!o!r!l!d']
Hope this helps!
listOne = ["hello","world"]
listTwo = ['!'.join([x for x in word]) for word in listOne]
How about this?
["!".join(s) for s in ["hello", "world"]]
Or more specific:
def turn(l):
return ["!".join(s) for s in l]
Edit: Removed wrapping of the string in list() as str.join takes every iterable
object (those that implement __iter__()), and, thus strings as well. Courtesy to #alKid.

Categories

Resources