Reputation:
I am trying to convert for example this list
F=[6, 9, 4, 3, 6, 8]
into a string that looks like this:
"6 9 4, 3 6 8"
the comma after 3 elements in this case is from the length of tuples in another list.
Can't figure out how to do this, I'll be grateful for any help!
Thank you!
Edit: Okay so I am trying to write a progam that "multiplies" to matrizes by adding the elements and finding the minimum. (ci,j = min {ai,k + bk,j})
What I got so far is
A="4 3 , 1 7"
B="2 5 9, 8 6 1"
A1 = A.split(",")
B1 = B.split(",")
A2 = [tuple(int(y) for y in x.split()) for x in A1]
B2 = [tuple(int(y) for y in x.split()) for x in B1]
D = []
for k in range(len(A2)):
for j in range(len(B2[0])):
C = []
for i in range(len(A2[0])):
N = (A2[k][i] + B2[i][j])
C.append(N)
D.append((min(C)))
So what I wrote gives me the right numbers, but in a list. I tried some codes from the internet but it won't work. The given strings A and B can be matrices of nxm so that I can't just cut the list to two pieces and add them together.
Thank you!
Upvotes: 1
Views: 75
Reputation: 48067
You may also use list comprehension expression using zip
as:
>>> my_list = [6, 9, 4, 3, 6, 8]
>>> n = 3
>>> ', '.join([' '.join(map(str, x)) for x in zip(*[my_list[i::n] for i in range(n)])])
'6 9 4, 3 6 8'
Upvotes: 2
Reputation: 350167
I would suggest this:
F=[6, 9, 4, 3, 6, 8, 9, 10]
size = 3
s = ', '.join([' '.join(map(str, F[i:i+size])) for i in range(0, len(F), size)])
Upvotes: 0
Reputation: 17064
Ok. 1 with regex also :)
import re
f = [6, 9, 4, 3, 6, 8]
a = re.sub(r"[\[\],]",r"", ''.join(str(f)))
print "\""+a[:5]+','+a[5:]+"\""
Output:
"6 9 4, 3 6 8"
Upvotes: 0
Reputation: 18632
One liner:
' '.join([str(i) if c != 3 else str(i)+', ' for c,i in enumerate(F,start=1)])
This will join all the elements by a space, adding a comma after the third element. Change the 3
in the line if you want to add the comma after a different element. The enumerate
function is counting the number of elements in F
with the index starting at 1
.
The join
string method will concatenate all elements of your list by ' '
(space).
Upvotes: 1
Reputation: 754
you can try below code:
F=[6, 9, 4, 3, 6, 8]
len_other_list = 3
F1 = F[:len_other_list]
F2 = F[len_other_list:]
reqd_string = ' '.join(map(str, F1))+', '+' '.join(map(str, F2))
Upvotes: 2