Integer list join using string.format - python

As Joining a list that has Integer values with Python, the integer list can be joined by converting str and then joining them.
BTW, I want to get foo bar 10 0 1 2 3 4 5 6 7 8 9 where several data are first(foo, bar), then the size of list 10 and elements follows.
I used string.format as
x = range(10)
out = '{} {} {} {}'.format('foo', 'bar', len(x), x)
out will be foo bar 10 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
To solve problem I can rewrite the code as
out = '{} {} {} '.format('foo', 'bar', len(x)) + ' '.join([str(i) for i in x])
It looks inconsistent (mixed string.format and join). I tried
slot = ' {}' * len(x)
out = ('{} {} {}' + slot).format('foo', 'bar', len(x), *x)
It still unattractive I think. Is there a way to join integer list using string.format only?

Since you favor attractiveness, want to use only one line and with format only, you can do
'{} {} {}{}'.format('foo', 'bar', len(x), ' {}' * len(x)).format(*x)
# foo bar 10 0 1 2 3 4 5 6 7 8 9

I might be missing the point of your question, but you could simply extend the approach you link to as follows:
>>> x = range(10)
>>> out = " ".join(map(str, ["foo", "bar", len(x)] + x))
>>> out
'foo bar 10 0 1 2 3 4 5 6 7 8 9'

You can simply use the print function for this:
>>> from __future__ import print_function #Required for Python 2
>>> print('foo', 'bar', len(x), *x)
foo bar 10 0 1 2 3 4 5 6 7 8 9

Related

Splitting number in list in K equal parts

I am trying to solve a problem in which I am dividing a list stick into equal size given by K.
Input: stick = [5, 9, 7], K = 4
This means that we have three sticks with lengths as 5, 9 and 7. We would like to come up with K=4 equal length sticks by cutting these three sticks. We would like to end up with K=4 equal length sticks.
Updated Explanation:
From the first stick with length 5, we can have one stick with length 4.
From the second stick with length 9, we can have two sticks with length 4.
From the third stick with length 7, we can have one stick with length 4.
My code is below:
stick = [5,7,9]
K=4
for i in range(len(stick)):
T = stick[i]%K
if T !=0:
print (stick[i],T)
else:
print (stick[i])
My code is giving me the below output
5 1
7 3
9 1
but how I can print the number + its addition like
5 = 4 + 1
7 = 4 + 3
9 = 4*2 + 1
My code is only giving me output 1,3,1
Expected output:
Input: stick = [5, 9, 7], K = 4
Output: 4
Explanation:
Cut arr[0] = 5 = 4 + 1
Cut arr[1] = 9 = 2 * 4 + 1
Cut arr[2] = 7 = 4 + 3
Example 2:
Input: stick[] = {5, 9, 7}, K = 3
Output: 5 \
Explanation:
Cut arr[0] = 5 = 5
Cut arr[1] = 9 = 5 + 4
Cut arr[2] = 5 = 5 + 2
It is best to construct a string depending on different conditions and print that instead:
stick = [5, 7, 8, 9]
K = 4
for i in range(len(stick)):
T = stick[i] % K
D = stick[i] // K
# Construct the multiplier text (* ...) if necessary
if D > 1:
multiplier = f" * {D}"
else:
multiplier = ""
# Construct the remainder (+ ...) text if necessary
if T:
remainder = f" + {T}"
else:
remainder = ""
# Print the final result
print(f"{stick[i]} = {K}{multiplier}{remainder}")
This should print:
5 = 4 + 1
7 = 4 + 3
8 = 4 * 2
9 = 4 * 2 + 1
Update: This answer assumes that K is the desired length as hinted in the original code posted in the question. If it is the number of splits the logic must be updated accordingly, but the answer to your actual question (i.e. "how to print in a specific way") stays the same.

Change the value of a variable given its name in a string [duplicate]

This question already has answers here:
How can I select a variable by (string) name?
(5 answers)
Closed 8 months ago.
I have a variable ab = 2; Now I let's say we have this variable as a string 'a'+'b'. Based on this and this I know how to print the value of ab when I call it as a string. My question is how I can modify it when I have it as a string.
For example:
class HELP:
def __init__(self):
self.ab = 2
self.a2b2 = 2
self.a3b3 = 2
self.a4b4 = 2
self.a5b5 = 2
count = 1
for k in [('a','b'),('a2','b2'),('a3','b3'),('a4','b4'),('a5','b5')]:
print(eval('self.'+k[0]+k[1])) # this will return the value
NewVar = 'self.'+'{}{}'.format(k[0],k[1])+'='+str(count*3)
globals()[NewVar] = count*3
count += 1
for k in [('a','b'),('a2','b2'),('a3','b3'),('a4','b4'),('a5','b5')]:
print(eval('self.'+k[0]+k[1]))
HELP()
will print:
2
2
2
2
2
2
2
2
2
2
but I expect to see:
2
2
2
2
2
3
6
9
12
15
I think the easiest way is to use a dictionary like:
d={'a':2,
'b':3
}
print(d['a']) # outputs 2
for k in ['a']:
d[k]=3
print(d['a']) # outputs 3
This method is very simple and effective. I also tried to do something like this once and it is so much easier just to use a dictionary.
>>> a2b2 = 2
>>> a3b3 = 2
>>> a4b4 = 2
>>> a5b5 = 2
>>> for i in range(2, 6):
... exec(f"a{i}b{i} = {i*3}")
...
>>> a2b2
6
>>> a3b3
9
>>> a4b4
12
>>> a5b5
15
You can do like this.
>>> foo = 5
>>> foo
5
>>> exec("foo = 1337")
>>> foo
1337
You can do it with the exec function. It's not very safe but it works.

Subtraction of one string values from another string values

I got two strings, called string1 and string2. Both consists of 6 different numbers.
What i would like to do in Python is to substract the values in string1 from the values in string2. How do I do this? I Guess this involves a for loop, since I only want to substract the first value in string1 from the first value in string2. And substract the second value from string1 from the second value in string2 etc.
So if string 1 got the numbers
2 5 8 9 6 3
and string 2 got the numbers
2 3 5 9 3 2
I want to take "string1" minus "string2" to get
0 2 3 0 3 1
Any suggestions?
You can achieve this with split(), zip(), and join():
" ".join([str(int(a) - int(b)) for a, b in zip(s1.split(), s2.split())])
Building on #pault answer, you can have the following variation (removed the calls to split(), added a conditional):
"".join([str(int(a) - int(b)) if a != ' ' else ' ' for a, b in zip(s1, s2)])
which is simply fancier way of doing:
" ".join([str(int(a) - int(b)) for a, b in zip(s1.replace(' ', ''), s2.replace(' ', ''))])
The latter might be more readable.
You can use regular expressions:
import re
s1 = '2 5 8 9 6 3'
s2 = '2 3 5 9 3 2'
new_string = ' '.join(str(a-b) for a, b in zip(map(int, re.findall('\d+', s1)), map(int, re.findall('\d+', s2))))
Output:
'0 2 3 0 3 1'
s1 = '2 5 8 9 6 3'
s2 = '2 3 5 9 3 2'
l1 = [int(x) for x in s1.split()]
l2 = [int(x) for x in s2.split()]
r1 = [v1 - v2 for v1, v2 in zip(l1, l2)]
.split() splits your string into a list based on where whitespace occurs (although you could provide it an argument to tell it to split on something else).
[int(x) for x in s1.split()] is a list comprehension. It's a one-line loop that does stuff for each value in a list (the split string). We need to convert the values in the split string into ints.
zip(l1, l2) takes the values in two lists and pairs them up. You'd need the lists to have the same number of elements for this to work (we do). From here, we use another list comprehension to pull out pairs of values and then take the difference.
edit (ty danihp): if you need the results to be a string, you can join the values in the list with ' '.join([str(x) for x in r1]) (this uses a space to separate elements in the list).
Step for step:
s1 = '2 5 8 9 6 3'
s2 = '2 3 5 9 3 2'
s3 = [int(x) for x in s1.split()] # split and convert to int
s4 = [int(x) for x in s2.split()] # split and convert to int
s5 = [] # result
for idx in range(0,len(s3)): # length are equal so this is ok
s5.append(s3[idx]-s4[idx]) # put into result
rv = " ".join([str(x) for x in s5]) # join result to string
print(s1)
print(s2)
print(s3)
print(s4)
print(s5)
print(rv)
Output:
2 5 8 9 6 3
2 3 5 9 3 2
[2, 5, 8, 9, 6, 3]
[2, 3, 5, 9, 3, 2]
[0, 2, 3, 0, 3, 1]
0 2 3 0 3 1
Since python is typed, you cannot subtact the strings: you have to convert each string to a list of integers and then subtract each one of the elements.
You can do this with only one loop:
s1 = '2 5 8 9 6 3'
s2 = '2 3 5 9 3 2'
list_diff = [int(x2) - int(x1) for x1, x2 in zip(s1.split(), s2.split())]
# or if you want the result as a string:
list_diff = [str(int(x1) - int(x2)) for x1, x2 in zip(s1.split(), s2.split())]
result = " ".join(list_diff)

Python: print without overwriting printed lines

I have
for i in range(0, 11): print i, "\n", i
I'd like my python program to print this way for each for loop
1st loop:
1
1
2nd loop:
1
2
2
1
3rd loop:
1
2
3
3
2
1
I've tried using \r\n or \033[1A but they just overwrite the previous line. Is there a way I can "push" the outputted line down so I don't overwrite it?
One way to do this,
def foo(x, limit):
if x < limit :
print x
foo(x + 1, limit)
print x
foo(1, 11)
It's not possible to do it in 1 for loop as you're currently trying.
As I suggested, you can do it like this by using lists
>>> l1 = []
>>> l2 = []
>>> for i in range(0, 11):
... l1.append(i)
... l2 = [i] + l2
>>> l1.extend(l2)
>>> for i in l1:
... print i
0
1
2
3
4
5
6
7
8
9
10
10
9
8
7
6
5
4
3
2
1
0
Concatenation of two list generators.
>>> ladder = [x for x in range(5)] + [x for x in range(5,-1,-1)]
>>> ladder
[0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0]
>>> for x in ladder:
... print x
...
0
1
2
3
4
5
4
3
2
1
0
>>>
one of ways to solve this
def two_side_print(start, end):
text = [str(i) for i in range(start,end)]
print '\n'.join(text), '\n', '\n'.join(reversed(text))
two_side_print(1, 11)
Another option is to save the printed values in a list and print that list in reverse order in each loop iteration.
My suggestion:
l = []
for i in range(1, 5):
print 'Loop '+str(i) # This is to ease seeing the printing results
for val in l:
print val
print i
l.insert(len(l),i)
for val in reversed(l):
print val
The output for a loop iterating from 0 to 5:
Loop 1
1
1
Loop 2
1
2
2
1
Loop 3
1
2
3
3
2
1
Loop 4
1
2
3
4
4
3
2
1
I hope this is what you are looking for.
You can use a recursive function to help here:
def print_both_ways(start, end):
print(start)
if start != end:
print_both_ways(start+1, end)
print(start)
Usage:
print_both_ways(1,3) # prints 1,2,3,3,2,1 on separate lines

List Comprehension Nested Loop, Multiple Operations

Given a list like so:
[[1,2,3],[4,5,6],[7,8,9]]
I'm trying to get my output to look like this, with using only a list comprehension:
1 2 3
4 5 6
7 8 9
Right now I have this:
[print(x,end="") for row in myList for x in row]
This only outputs:
1 2 3 4 5 6 7 8 9
Is there a way to have it break to a new line after it processes each inner list?
You could do like the below.
>>> l = [[1,2,3],[4,5,6],[7,8,9]]
>>> for i in l:
print(' '.join(map(str, i)))
1 2 3
4 5 6
7 8 9
You can do as follows:
print("\n".join(" ".join(map(str, x)) for x in mylist))
Gives:
1 2 3
4 5 6
7 8 9
>>> l = [[1,2,3],[4,5,6],[7,8,9]]
>>> for line in l:
print(*line)
1 2 3
4 5 6
7 8 9
A good explanation of the star in this answer. tl;dr version: if line is [1, 2, 3], print(*line) is equivalent to print(1, 2, 3), which is distinct from print(line) which is print([1, 2, 3]).
I agree with Ashwini Chaudhary that using list comprehension to print is probably never the "right thing to do".
Marcin's answer is probably the best one-liner and Andrew's wins for readability.
For the sake of answering the question that was asked...
>>> from __future__ import print_function # python2.x only
>>> list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> [print(*x, sep=' ') for x in list]
1 2 3
4 5 6
7 8 9
[None, None, None]
Try this:
print("\n".join([' '.join([str(val) for val in list]) for list in my_list]))
In [1]: my_list = [[1,2,3],[4,5,6],[7,8,9]]
In [2]: print("\n".join([' '.join([str(val) for val in list]) for list in my_list]))
1 2 3
4 5 6
7 8 9

Categories

Resources