get rid of commas in a list python - python

I have a list [1,2,4,7,5,2] where I want to get rid of the commas to make it [1 2 4 7 5 2]
how would I go about this?
np.random.randint(0,4,12) will print out like [0 3 4 1 3 4 2 1 2 4 3 4] and thats the kind of thing I want :)

You could do this:
out = '[' + ' '.join(str(item) for item in numbers)+ ']'
print out

In [7]: data = [1,2,4,7,5,2]
In [11]: '[{}]'.format(' '.join(map(str, data)))
Out[11]: '[1 2 4 7 5 2]'
or,
In [14]: str(data).replace(',','')
Out[14]: '[1 2 4 7 5 2]'

If you want a numpy ndarray, use:
np.array([1, 2, 4, 7, 5, 2])

Related

How I can get the loop result as list or string

I write this code
for i in range(1,6):
for m in range(i):
print(i)
And I get the output like this:
1
2
2
3
3
3
4
4
4
4
5
5
5
5
5
How I can get the output as an iterator (list or tuple) like this
1[1]
2[2,2]
or simple string like this (In each category of numbers, we return to the line)
1
22
333
You can do this for iterable format output:
for i in range(1,6):
print(i, [i]*i)
output ->
1 [1]
2 [2, 2]
3 [3, 3, 3]
4 [4, 4, 4, 4]
5 [5, 5, 5, 5, 5]
or this for string format output:
for i in range(1,6):
print(str(i)*i)
output ->
1
22
333
4444
55555

How to change a list [1,2,3] into 1 2 3 with spaces in between?

I created a list
x = list(range(0,5))
which gives the result [0,1,2,3,4] but I want to convert it as 0 1 2 3 4
How do I do that?
myList = [1, 2, 3]
print(' '.join(myList))
Try using * to unpack the list
print(*[1,2,3]) # -> 1 2 3

Python how to add two elements of a dataframe keeping the result before

I would like to add values ​​in my dataframe between them but each time keeping the result of the addition before.
To put it simply, i would like to do :
df['col'][0]
df['col'][0] + df['col'][1]
df['col'][0] + df['col'][1] + df['col'][2]
df['col'][0] + df['col'][1] + df['col'][2] + df['col'][3]
.
.
.
df['col'][0] + ... + df['col'][n]
I would like to put each of the values ​​in a list.
Could you help me ?
thank you so much
You can use cumsum:
In [679]: df = pd.DataFrame({"A":[5, 3, 6, 4],
...: "B":[11, 2, 4, 3],
...: "C":[4, 3, 8, 5],
...: "D":[5, 4, 2, 8]})
In [680]: df
Out[680]:
A B C D
0 5 11 4 5
1 3 2 3 4
2 6 4 8 2
3 4 3 5 8
In [682]: df.A.cumsum(axis=0)
Out[682]:
0 5
1 8
2 14
3 18

Shuffle "coupled" elements in python array

Let's say I have this array:
np.arange(9)
[0 1 2 3 4 5 6 7 8]
I would like to shuffle the elements with np.random.shuffle but certain numbers have to be in the original order.
I want that 0, 1, 2 have the original order.
I want that 3, 4, 5 have the original order.
And I want that 6, 7, 8 have the original order.
The number of elements in the array would be multiple of 3.
For example, some possible outputs would be:
[ 3 4 5 0 1 2 6 7 8]
[ 0 1 2 6 7 8 3 4 5]
But this one:
[2 1 0 3 4 5 6 7 8]
Would not be valid because 0, 1, 2 are not in the original order
I think that maybe zip() could be useful here, but I'm not sure.
Short solution using numpy.random.shuffle and numpy.ndarray.flatten functions:
arr = np.arange(9)
arr_reshaped = arr.reshape((3,3)) # reshaping the input array to size 3x3
np.random.shuffle(arr_reshaped)
result = arr_reshaped.flatten()
print(result)
One of possible random results:
[3 4 5 0 1 2 6 7 8]
Naive approach:
num_indices = len(array_to_shuffle) // 3 # use normal / in python 2
indices = np.arange(num_indices)
np.random.shuffle(indices)
shuffled_array = np.empty_like(array_to_shuffle)
cur_idx = 0
for idx in indices:
shuffled_array[cur_idx:cur_idx+3] = array_to_shuffle[idx*3:(idx+1)*3]
cur_idx += 3
Faster (and cleaner) option:
num_indices = len(array_to_shuffle) // 3 # use normal / in python 2
indices = np.arange(num_indices)
np.random.shuffle(indices)
tmp = array_to_shuffle.reshape([-1,3])
tmp = tmp[indices,:]
tmp.reshape([-1])

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