Related
I have a list like ;
list1 = ['ex1_a','ex2_b','ex3_b']
I want to split it like this to the new list ;
newlist = ['ex1 a', 'ex2 b', 'ex3 b']
I try to do it like this but it didn't work. How can I do this?
for x in list1:
newlist = " ".join(x.split("_"))
You can use str.replace instead str.split/str.join:
list1 = ["ex1_a", "ex2_b", "ex3_b"]
newlist = [v.replace("_", " ") for v in list1]
print(newlist)
Prints:
['ex1 a', 'ex2 b', 'ex3 b']
If you want to use str.split:
newlist = [" ".join(v.split("_")) for v in list1]
I have two list in same size in python and want to merge them to become one list with the same number size as before
first one :
['add ', 'subtract ', 'multiply ', 'divide ']
second one :
[3, 2, 3, 2]
and i want output came like :
['add 3', 'subtract 2', 'multiply 3', 'divide 2']
How can I do that?
I tried this:
list3 = functions_name + main_function_count
but the output is :
['add ', 'subtract ', 'multiply ', 'divide ', 3, 2, 3, 2]
Use a combination of list comprehension with zip and f-strings
list1 = ['add ', 'subtract ', 'multiply ', 'divide ']
list2 = [3, 2, 3, 2]
result = [f'{x} {y}' for x, y in zip(list1, list2)]
+ is adding the lists themselves, you want to apply + to each element.
ops = ['add ', 'subtract ', 'multiply ', 'divide ']
nums = [3, 2, 3, 2]
list3 = [op+str(n) for op, n in zip(ops, nums)]
# or using an fstring to remove "+" entirely
list3 = [f"{op}{n}" for op, n in zip(ops, nums)]
zip lets you iterate multiple "iterables", like lists, in parallel.
edit: changed n to str(n), fstring
Using list comprehension:
a = ['add ', 'subtract ', 'multiply ', 'divide ']
b = [3, 2, 3, 2]
# Here:
# zip(a, b) iterates through a and b in parallel
# for x,y assigns corressponding values from a and b
# f'{x} {y}' combines the values with a separating space.
# [...] is a "list comprehension"
c = [ f'{x} {y}' for x,y in zip(a, b) ]
print(c)
Outputs:
['add 3', 'subtract 2', 'multiply 3', 'divide 2']
You could do it like this:
list1 = ['add ', 'subtract ', 'multiply ', 'divide ']
list2 = [3, 2, 3, 2]
list3 = []
for y,x in enumerate(list1):
list3.append("%s%d" % (x,list2[y]))
You can try it:
list1 = ['add ', 'subtract ', 'multiply ', 'divide ']
list2 = [3, 2, 3, 2]
result = []
for i,j in zip(list1,list2):
result.append(str(i)+str(j))
print(result)
Output:
['add 3', 'subtract 2', 'multiply 3', 'divide 2']
This is a good case for a "List comprehension"!
You can essentially make a small for loop in a python 1-liner as below. Note that to concatenate the values you have to declare the int as a str. You could also do this with f-strings, but I think this is a clearer explanation:
l1 = [1,2,3,4]
l2 = ['a','b','c','d']
result = [str(la)+lb for la,lb in zip(l1,l2)]
returns
result = ['1a', '2b', '3c', '4d']
Here we're using zip() it index along two lists simultaneously in the list comprehension, and simply concatenating the elements as we go along.
EDIT: To do this without a plus, we can use an f-string as follows:
result = [f"{la} {lb}" for la,lb in zip(l1,l2)]
This returns the same value, but doesn't use a plus operator (and you don't have to declare a type str(), the f-string does that for you.)
You can add each element together, making sure that numbers are converted to strings:
functions_name = ['add ', 'subtract ', 'multiply ', 'divide ']
main_function_count = [3, 2, 3, 2]
list3 = [name+str(count) for name,count in zip(functions_name, main_function_count)]
print(list3)
Output as requested
Or, without using + to concatenate strings:
list3 = [f'{name}{count}' for name,count in zip(functions_name, main_function_count)]
One more, seems I'll never get tired of pointing out that map can use multiple iterables:
ops = ['add ', 'subtract ', 'multiply ', 'divide ']
nums = [3, 2, 3, 2]
list3 = list(map('{}{}'.format, ops, nums))
This question already has answers here:
How to remove leading and trailing spaces from strings in a Python list
(3 answers)
Remove trailing newline from the elements of a string list
(7 answers)
Closed 1 year ago.
How do I remove the spaces at the beginning of each string in a list?
List = [' a', ' b', ' c']
Here is what I tried, but the list remained the same:
unique_items_1 = []
for i in unique_items:
j = i.replace('^ +', '')
unique_items_1.append(j)
print(List)
My expected result was:
List = ['a', 'b', 'c']
Use str.lstrip in a list comprehension:
my_list = [' a', ' b', ' c']
my_list = [i.lstrip() for i in my_list]
print(my_list) # ['a', 'b', 'c']
To remove the leading white spaces, you can use the lstrip function.
In your case, for the list:
result = [x.lstrip() for x in List]
print(result)
For removing trailing spaces:
result = [x.rstrip() for x in List]
print(result)
The below code should work in general to remove all white spaces:
result = [x.replace(' ','') for x in List
print(result)
List = [' a',' b',' c']
print(List) # [' a', ' b', ' c']
List_Trimmed = [*map(lambda x: x.lstrip(), List)]
print(List_Trimmed) # ['a', 'b', 'c']
You can use strip():
for i in unique_items:
j = i.strip()
unique_items_1.append(j)
strip() removes spaces.
You can also use lstrip().
I have a set of numbers that I want to align considering the comma:
10 3
200 4000,222 3 1,5
200,21 0,3 2
30000 4,5 1
mylist = [['10', '3', '', ''],
['200', '4000,222', '3', '1,5'],
['200,21', '', '0,3', '2'],
['30000', '4,5', '1', '']]
What I want is to align this list considering the comma:
expected result:
mylist = [[' 10 ', ' 3 ', ' ', ' '],
[' 200 ', '4000,222', '3 ', '1,5'],
[' 200,21', ' ', '0,3', '2 '],
['30000 ', ' 4,5 ', '1 ', ' ']]
I tried to turn the list:
mynewlist = list(zip(*mylist))
and to find the longest part after the comma in every sublist:
for m in mynewlist:
max([x[::-1].find(',') for x in m]
and to use rjust and ljust but I don't know how to ljust after a comma and rjust before the comma, both in the same string.
How can I resolve this without using format()?
(I want to align with ljust and rjust)
Here's another approach that currently does the trick. Unfortunately, I can't see any simple way to make this work, maybe due to the time :-)
Either way, I'll explain it. r is the result list created before hand.
r = [[] for i in range(4)]
Then we loop through the values and also grab an index with enumerate:
for ind1, vals in enumerate(zip(*mylist)):
Inside the loop we grab the max length of the decimal digits present and the max length of the word (the word w/o the decimal digits):
l = max(len(v.partition(',')[2]) for v in vals) + 1
mw = max(len(v if ',' not in v else v.split(',')[0]) for v in vals)
Now we go through the values inside the tuple vals and build our results (yup, can't currently think of a way to avoid this nesting).
for ind2, v in enumerate(vals):
If it contains a comma, it should be formatted differently. Specifically, we rjust it based on the max length of a word mw and then add the decimal digits and any white-space needed:
if ',' in v:
n, d = v.split(',')
v = "".join((n.rjust(mw),',', d, " " * (l - 1 - len(d))))
In the opposite case, we simply .rjust and then add whitespace:
else:
v = "".join((v.rjust(mw) + " " * l))
finally, we append to r.
r[ind1].append(v)
All together:
r = [[] for i in range(4)]
for ind1, vals in enumerate(zip(*mylist)):
l = max(len(v.partition(',')[2]) for v in vals) + 1
mw = max(len(v if ',' not in v else v.split(',')[0]) for v in vals)
for ind2, v in enumerate(vals):
if ',' in v:
n, d = v.split(',')
v = "".join((n.rjust(mw),',', d, " " * (l - 1 - len(d))))
else:
v = "".join((v.rjust(mw) + " " * l))
r[ind1].append(v)
Now, we can print it out:
>>> print(*map(list,zip(*r)), sep='\n)
[' 10 ', ' 3 ', ' ', ' ']
[' 200 ', '4000,222', '3 ', '1,5']
[' 200,21', ' ', '0,3', '2 ']
['30000 ', ' 4,5 ', '1 ', ' ']
Here's a bit different solution that doesn't transpose my_list but instead iterates over it twice. On the first pass it generates a list of tuples, one for each column. Each tuple is a pair of numbers where first number is length before comma and second number is length of comma & everything following it. For example '4000,222' results to (4, 4). On the second pass it formats the data based on the formatting info generated on first pass.
from functools import reduce
mylist = [['10', '3', '', ''],
['200', '4000,222', '3', '1,5'],
['200,21', '', '0,3', '2'],
['30000', '4,5', '1', '']]
# Return tuple (left part length, right part length) for given string
def part_lengths(s):
left, sep, right = s.partition(',')
return len(left), len(sep) + len(right)
# Return string formatted based on part lengths
def format(s, first, second):
left, sep, right = s.partition(',')
return left.rjust(first) + sep + right.ljust(second - len(sep))
# Generator yielding part lengths row by row
parts = ((part_lengths(c) for c in r) for r in mylist)
# Combine part lengths to find maximum for each column
# For example data it looks like this: [[5, 3], [4, 4], [1, 2], [1, 2]]
sizes = reduce(lambda x, y: [[max(z) for z in zip(a, b)] for a, b in zip(x, y)], parts)
# Format result based on part lengths
res = [[format(c, *p) for c, p in zip(r, sizes)] for r in mylist]
print(*res, sep='\n')
Output:
[' 10 ', ' 3 ', ' ', ' ']
[' 200 ', '4000,222', '3 ', '1,5']
[' 200,21', ' ', '0,3', '2 ']
['30000 ', ' 4,5 ', '1 ', ' ']
This works for python 2 and 3. I didn't use ljust or rjust though, i just added as many spaces before and after the number as are missing to the maximum sized number in the column:
mylist = [['10', '3', '', ''],
['200', '4000,222', '3', '1,5'],
['200,21', '', '0,3', '2'],
['30000', '4,5', '1', '']]
transposed = list(zip(*mylist))
sizes = [[(x.index(",") if "," in x else len(x), len(x) - x.index(",") if "," in x else 0)
for x in l] for l in transposed]
maxima = [(max([x[0] for x in l]), max([x[1] for x in l])) for l in sizes]
withspaces = [
[' ' * (maxima[i][0] - sizes[i][j][0]) + number + ' ' * (maxima[i][1] - sizes[i][j][1])
for j, number in enumerate(l)] for i, l in enumerate(transposed)]
result = list(zip(*withspaces))
Printing the result in python3:
>>> print(*result, sep='\n')
(' 10 ', ' 3 ', ' ', ' ')
(' 200 ', '4000,222', '3 ', '1,5')
(' 200,21', ' ', '0,3', '2 ')
('30000 ', ' 4,5 ', '1 ', ' ')
This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Closed 9 years ago.
If you had a long list of lists in the format [['A',1,2],['B',3,4]] and you wanted to combine it into ['A, 1, 2', 'B, 3, 4'] is there a easy list comprehension way to do so?
I do it like this:
this_list = [['A',1,2],['B',3,4]]
final = list()
for x in this_list:
final.append(', '.join([str(x) for x in x]))
But is this possible to be done as a one-liner?
Thanks for the answers. I like the map() based one. I have a followup question - if the sublists were instead of the format ['A',0.111,0.123456] would it be possible to include a string formatting section in the list comprehension to truncate such as to get out 'A, 0.1, 0.12'
Once again with my ugly code it would be like:
this_list = [['A',0.111,0.12345],['B',0.1,0.2]]
final = list()
for x in this_list:
x = '{}, {:.1f}, {:.2f}'.format(x[0], x[1], x[2])
final.append(x)
I solved my own question:
values = ['{}, {:.2f}, {:.3f}'.format(c,i,f) for c,i,f in values]
>>> lis = [['A',1,2],['B',3,4]]
>>> [', '.join(map(str, x)) for x in lis ]
['A, 1, 2', 'B, 3, 4']
You can use nested list comprehensions with str.join:
>>> lst = [['A',1,2],['B',3,4]]
>>> [", ".join([str(y) for y in x]) for x in lst]
['A, 1, 2', 'B, 3, 4']
>>>
li = [['A',1,2],['B',3,4],['A',0.111,0.123456]]
print [', '.join(map(str,sli)) for sli in li]
def func(x):
try:
return str(int(str(x)))
except:
try:
return '%.2f' % float(str(x))
except:
return str(x)
print map(lambda subli: ', '.join(map(func,subli)) , li)
return
['A, 1, 2', 'B, 3, 4', 'A, 0.111, 0.123456']
['A, 1, 2', 'B, 3, 4', 'A, 0.11, 0.12']