Convert a list to a string in another list - python

I am working on the lists but I had a problem.
There is a list as follows:
First_last_Name = [['hassan','abasi'],['mohammad','sajadi'],['bahman','mardomani'],['sarah','masti']]
Now we want to convert it as follows:
First_last_Name = ['hassan abasi','mohammad sajadi','bahman mardomani','sarah masti']
I want to try to write it in one line with lambda.
The code I am trying to apply in one line is as follows:
full_str = [(lambda x: str(x))(x) for x in First_last_Name]
output :
["['hassan', 'abasi']",
"['mohammad', 'sajadi']",
"['bahman', 'mardomani']",
"['sarah', 'masti']"]
But I can't delete that internal list and turn it into a string.

You can do it with a list comprehension and join
result = [" ".join(i) for i in First_last_Name]
Result:
['hassan abasi', 'mohammad sajadi', 'bahman mardomani', 'sarah masti']

First_last_Name = [['hassan','abasi'],['mohammad','Sajadi'],['bahman','mardomani'],['sarah','masti']]
new_list = [ " ".join(i) for i in First_last_Name]

I'd prefer #sembei-norimaki 's solution. But as you asked about lambda:
result = list(map(lambda x: ' '.join(x), First_last_Name))
or even simpler:
result = list(map(' '.join, First_last_Name))

Related

Converting a list with multiple values into a dictionary

I have the following list and am wanting to convert it into a dictionary where the 4 digit value at the start of each item becomes the id.
['3574,A+,2021-03-24', '3575,O+,2021-04-03', '3576,AB-,2021-04-09', '3580,AB+,2021-04-27', '3589,A+,2021-05-08', '3590,B-,2021-05-11']
I have tried many different methods but it doesn't seem to work.
You can use str.split, map and dictionary comprehension
# data holds the list you have provided
{splitted[0]:splitted[1:] for splitted in map(lambda item:item.split(','), data)}
OUTPUT:
Out[35]:
{'3574': ['A+', '2021-03-24'],
'3575': ['O+', '2021-04-03'],
'3576': ['AB-', '2021-04-09'],
'3580': ['AB+', '2021-04-27'],
'3589': ['A+', '2021-05-08'],
'3590': ['B-', '2021-05-11']}
You can use dictionary comprehension with str.split:
lst = [
"3574,A+,2021-03-24",
"3575,O+,2021-04-03",
"3576,AB-,2021-04-09",
"3580,AB+,2021-04-27",
"3589,A+,2021-05-08",
"3590,B-,2021-05-11",
]
out = {int(v.split(",")[0]): v.split(",")[1:] for v in lst}
print(out)
Prints:
{
3574: ["A+", "2021-03-24"],
3575: ["O+", "2021-04-03"],
3576: ["AB-", "2021-04-09"],
3580: ["AB+", "2021-04-27"],
3589: ["A+", "2021-05-08"],
3590: ["B-", "2021-05-11"],
}
Here is the code to do what I believe you asked for. I have also added comments in the code for a bit more clarification.
my_list = ['3574,A+,2021-03-24',
'3575,O+,2021-04-03',
'3576,AB-,2021-04-09',
'3580,AB+,2021-04-27',
'3589,A+,2021-05-08',
'3590,B-,2021-05-11']#your list
my_dict = {}#The dictionary you want to put the list into
print("Your list:", my_list, "\n")
for item in my_list:#cycles through every item in your list
ID, value = item.split(",", 1)#Splits the item in your list only once (when it sees the first comma)
print(ID + ": " + value)
my_dict[ID] = value#Add the ID and value to your dictionary
print("\n" + "Your desired dictionary:", my_dict)
Which outputs this:
Your list: ['3574,A+,2021-03-24', '3575,O+,2021-04-03', '3576,AB-,2021-04-09', '3580,AB+,2021-04-27', '3589,A+,2021-05-08', '3590,B-,2021-05-11']
3574: A+,2021-03-24
3575: O+,2021-04-03
3576: AB-,2021-04-09
3580: AB+,2021-04-27
3589: A+,2021-05-08
3590: B-,2021-05-11
Your desired dictionary: {'3574': 'A+,2021-03-24', '3575': 'O+,2021-04-03', '3576': 'AB-,2021-04-09', '3580': 'AB+,2021-04-27', '3589': 'A+,2021-05-08', '3590': 'B-,2021-05-11'}
Enjoy!
TRY:
result = dict(i.split(',', 1) for i in lst)
OUTPUT:
{'3574': 'A+,2021-03-24',
'3575': 'O+,2021-04-03',
'3576': 'AB-,2021-04-09',
'3580': 'AB+,2021-04-27',
'3589': 'A+,2021-05-08',
'3590': 'B-,2021-05-11'}

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)

How to iteratively split a string using backward combinations?

I have a list of strings that look like this:
['C04.123.123.123', 'C03.456.456.456', 'C05.789.789.789']
I'm trying to split each string so I get different backward combinations of splits on the period delimiter. Basically, if I only take the example of the first string, I want to get:
['C04.123.123.123', 'C04.123.123', 'C04.123', 'C04']
How can I achieve this? I've tried looking into itertools.combinations and the standard split features but no luck.
One-line, easy to understand (was less easy to tune :)), using str.rsplit with maxsplit gradually increasing up to the number of dots:
lst = ['C04.123.123.123', 'C03.456.456.456', 'C05.789.789.789']
result = [x.rsplit(".",i)[0] for x in lst for i in range(x.count(".")+1) ]
result:
['C04.123.123.123',
'C04.123.123',
'C04.123',
'C04',
'C03.456.456.456',
'C03.456.456',
'C03.456',
'C03',
'C05.789.789.789',
'C05.789.789',
'C05.789',
'C05']
The only thing that annoys me is that it calls split a lot just to keep the first element. Too bad there isn't a built-in lazy split function we could call next on.
You can use a list comprehension:
d = ['C04.123.123.123', 'C03.456.456.456', 'C05.789.789.789']
new_d = [a+('.' if i else '')+'.'.join(i) for a, *c in map(".".split, d)
for i in [c[:h] for h in range(len(c)+1)][::-1]]
Output:
['C04.123.123.123', 'C04.123.123', 'C04.123', 'C04', 'C03.456.456.456', 'C03.456.456', 'C03.456', 'C03', 'C05.789.789.789', 'C05.789.789', 'C05.789', 'C05']
start_list = ['C04.123.123.123', 'C03.456.456.456', 'C05.789.789.789']
final_list = []
for item in start_list:
broke_up = item.split('.')
temp = []
full_item = []
for sect in broke_up:
temp.append(sect)
full_item.append(".".join(temp))
final_list.extend(full_item)
print(final_list)
Alternatively you can final_list.append(full_item) to keep seperate lists for each string in the original list.
Try this:
list(accumulate(s.split('.'), lambda a, b: a + '.' + b))[::-1]
You can use itertools.accumulate:
from itertools import accumulate
s = 'C04.123.123.123'
# define the incremental step
append = lambda s, e: s + '.' + e
result = list(accumulate(s.split('.'), append))[::-1]

Make List to String Python

I want to make list data to string.
My list data like this :
[['data1'],['data2'],['data3']]
I want to convert to string like this :
"[data1] [data2] [data3]"
I try to use join like this :
data=[['data1'],['data2'],['data3']]
list=" ".join(data)
But get error like this :
string= " ".join(data)
TypeError: sequence item 0: expected string, list found
Can somebody help me?
Depending on how closely you want the output to conform to your sample, you have a few options, show here in ascending order of complexity:
>>> data=[['data1'],['data2'],['data3']]
>>> str(data)
"[['data1'], ['data2'], ['data3']]"
>>> ' '.join(map(str, data))
"['data1'] ['data2'] ['data3']"
>>> ' '.join(map(str, data)).replace("'", '')
'[data1] [data2] [data3]'
Keep in mind that, if your given sample of data doesn't match your actual data, these methods may or may not produce the desired results.
Have you tried?
data=[['data1'],['data2'],['data3']]
t = map(lambda x : str(x), data)
print(" ".join(t))
Live demo - https://repl.it/BOaS
In Python 3.x , the elements of the iterable for str.join() has to be a string .
The error you are getting - TypeError: sequence item 0: expected string, list found - is because the elements of the list you pass to str.join() is list (as data is a list of lists).
If you only have a single element per sublist, you can simply do -
" ".join(['[{}]'.format(x[0]) for x in data])
Demo -
>>> data=[['data1'],['data2'],['data3']]
>>> " ".join(['[{}]'.format(x[0]) for x in data])
'[data1] [data2] [data3]'
If the sublists can have multiple elements and in your output you want those multiple elements separated by a , . You can use a list comprehension inside str.join() to create a list of strings as you want. Example -
" ".join(['[{}]'.format(','.join(x)) for x in data])
For some other delimiter other than ',' , use that in - '<delimiter>'.join(x) .
Demo -
>>> data=[['data1'],['data2'],['data3']]
>>> " ".join(['[{}]'.format(','.join(x)) for x in data])
'[data1] [data2] [data3]'
For multiple elements in sublist -
>>> data=[['data1','data1.1'],['data2'],['data3','data3.1']]
>>> " ".join(['[{}]'.format(','.join(x)) for x in data])
'[data1,data1.1] [data2] [data3,data3.1]'
>>> import re
>>> l = [['data1'], ['data2'], ['data3']]
>>> s = ""
>>> for i in l:
s+= re.sub(r"\'", "", str(i))
>>> s
'[data1][data2][data3]'
How about this?
data = [['data1'], ['data2'], ['data3']]
result = " ".join('[' + a[0] + ']' for a in data)
print(result)
How about this:
In [13]: a = [['data1'],['data2'],['data3']]
In [14]: import json
In [15]: temp = " ".join([json.dumps(x) for x in a]).replace("\"", "")
In [16]: temp
Out[16]: '[data1] [data2] [data3]'
Try the following. This can also be achieved by "Reduce":
from functools import reduce
data = [['data1'], ['data2'], ['data3']]
print(list(reduce(lambda x,y : x+y, data)))
output: ['data1', 'data2', 'data3']

concatenating selected elements in a list of lists in python

I have a (python) list of lists as below
biglist=[ ['1','123-456','hello','there'],['2','987-456','program'],['1','123-456','list','of','lists'] ]
I need to get this in the following format
biglist_modified=[ ['1','123-456','hello there'],['2','987-456','program'],['1','123-456','list of lists'] ]
I need to concatenate the third element onwards in each inner list.I tried to do this by using list comprehensions,
def modify_biglist(bigl):
ret =[]
for alist in bigl:
alist[2] = ' '.join(alist[2:])
del alist[3:]
ret.append(alist)
return ret
This does the job..but it looks a bit convoluted -having a local variable ret and using del? Can someone suggest something better
[[x[0], x[1], " ".join(x[2:])] for x in biglist]
or, in-place:
for x in biglist:
x[2:] = [" ".join(x[2:])]
To modify your list in place, you could use the following simplification of your code:
for a in big_list:
a[2:] = [" ".join(a[2:])]
This ought to do it:
[x[:2] + [" ".join(x[2:])] for x in biglist]
Slightly shorter.

Categories

Resources