Python input array one line - python

I want to be able to input something like [1, 2, 3, 4, 5, 6, 7] and have it return another array like ['a'. 'b', 'c'] How do I do this?
I have tried this but I can only do single numbers.
arr = list(map(int, input("message > ").split()))

You can use string.ascii_lowercase - which is a string of lowercased letters - along with a list comprehension as shown below.
To handle the case of multi-digit numbers, you'll need to separate the numbers in the input, for example using a space character, and then split on this character when processing the user input.
import string
arr = [string.ascii_lowercase[int(i) - 1]
for i in input("message > ").split(' ')]
print(arr)
Sample interaction with user:
message > 1 3 5 7 9 11
['a', 'c', 'e', 'g', 'i', 'k']

My understanding is that you would like to make multiple lists inside a list from a single input.
If you know how many arrays you want you can use:
arr = [list(map(int, input("message > ").split())) for _ in range(3)]
Output:
message > 1 2 3
message > 1 4 5
message > 1 3 4
[[1, 2, 3], [1, 4, 5], [1, 3, 4]]
if you don't know how many you could use:
arr = [[i] for i in list(input("message > ").split(","))]
Output:
message > 1 2 3, 1 4 5, 1 3 4
[['1 2 3'], [' 1 4 5'], [' 1 3 4']]
In the second just separate the inputs with commas.

Related

Storing list of lists in matrix format [duplicate]

I have a list of lists:
a = [[1, 3, 4], [2, 5, 7]]
I want the output in the following format:
1 3 4
2 5 7
I have tried it the following way , but the outputs are not in the desired way:
for i in a:
for j in i:
print(j, sep=' ')
Outputs:
1
3
4
2
5
7
While changing the print call to use end instead:
for i in a:
for j in i:
print(j, end = ' ')
Outputs:
1 3 4 2 5 7
Any ideas?
Iterate through every sub-list in your original list and unpack it in the print call with *:
a = [[1, 3, 4], [2, 5, 7]]
for s in a:
print(*s)
The separation is by default set to ' ' so there's no need to explicitly provide it. This prints:
1 3 4
2 5 7
In your approach you were iterating for every element in every sub-list and printing that individually. By using print(*s) you unpack the list inside the print call, this essentially translates to:
print(1, 3, 4) # for s = [1, 3, 4]
print(2, 5, 7) # for s = [2, 5, 7]
oneliner:
print('\n'.join(' '.join(map(str,sl)) for sl in l))
explanation:
you can convert list into str by using join function:
l = ['1','2','3']
' '.join(l) # will give you a next string: '1 2 3'
'.'.join(l) # and it will give you '1.2.3'
so, if you want linebreaks you should use new line symbol.
But join accepts only list of strings. For converting list of things to list of strings, you can apply str function for each item in list:
l = [1,2,3]
' '.join(map(str, l)) # will return string '1 2 3'
And we apply this construction for each sublist sl in list l
You can do this:
>>> lst = [[1, 3, 4], [2, 5, 7]]
>>> for sublst in lst:
... for item in sublst:
... print item, # note the ending ','
... print # print a newline
...
1 3 4
2 5 7
a = [[1, 3, 4], [2, 5, 7]]
for i in a:
for j in i:
print(j, end = ' ')
print('',sep='\n')
output:
1 3 4
2 5 7
lst = [[1, 3, 4], [2, 5, 7]]
def f(lst ):
yield from lst
for x in f(lst):
print(*x)
using "yield from"...
Produces Output
1 3 4
2 5 7
[Program finished]
There is an alternative method to display list rather than arranging them in sub-list:
tick_tack_display = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
loop_start = 0
count = 0
while loop_start < len(tick_tack_display):
print(tick_tack_display[loop_start], end = '')
count +=1
if count - 3 == 0:
print("\n")
count = 0
loop_start += 1
OUTPUT :
123
456
789
I believe this is pretty simple:
a = [[1, 3, 4], [2, 5, 7]] # defines the list
for i in range(len(a)): # runs for every "sub-list" in a
for j in a[i]: # gives j the value of each item in a[i]
print(j, end=" ") # prints j without going to a new line
print() # creates a new line after each list-in-list prints
output
1 3 4
2 5 7
def print_list(s):
for i in range(len(s)):
if isinstance(s[i],list):
k=s[i]
print_list(k)
else:
print(s[i])
s=[[1,2,[3,4,[5,6]],7,8]]
print_list(s)
you could enter lists within lists within lists ..... and yet everything will be printed as u expect it to be.
Output:
1
2
3
4
5
6
7
8
There's an easier one-liner way:
a = [[1, 3, 4], [2, 5, 7]] # your data
[print(*x) for x in a][0] # one-line print
And the result will be as you want it:
1 3 4
2 5 7
Make sure you add the [0] to the end of the list comprehension, otherwise, the last line would be a list of None values equal to the length of your list.

Generate random array of integers with a number of appearance of each integer

I need to create a random array of 6 integers between 1 and 5 in Python but I also have another data say a=[2 2 3 1 2] which can be considered as the capacity. It means 1 can occur no more than 2 times or 3 can occur no more than 3 times.
I need to set up a counter for each integer from 1 to 5 to make sure each integer is not generated by the random function more than a[i].
Here is the initial array I created in python but I need to find out how I can make sure about the condition I described above. For example, I don't need a solution like [2 1 5 4 5 4] where 4 is shown twice or [2 2 2 2 1 2].
solution = np.array([np.random.randint(1,6) for i in range(6)])
Even if I can add probability, that should work. Any help is appreciated on this.
You can create an pool of data that have the most counts and then pick from there:
import numpy as np
a = [2, 2, 3, 1, 2]
data = [i + 1 for i, e in enumerate(a) for _ in range(e)]
print(data)
result = np.random.choice(data, 6, replace=False)
print(result)
Output
[1, 1, 2, 2, 3, 3, 3, 4, 5, 5]
[1 3 2 2 3 1]
Note that data is array that has for each element the specified count, then we pick randomly from data this way we ensure that you won't have more elements that the specify count.
UPDATE
If you need that each number appears at least one time, you can start with a list of each of the numbers, sample from the rest and then shuffle:
import numpy as np
result = [1, 2, 3, 4, 5]
a = [1, 1, 2, 0, 1]
data = [i + 1 for i, e in enumerate(a) for _ in range(e)]
print(data)
result = result + np.random.choice(data, 1, replace=False).tolist()
np.random.shuffle(result)
print(result)
Output
[1, 2, 3, 3, 5]
[3, 4, 2, 5, 1, 2]
Notice that I subtract 1 from each of the original values of a, also the original 6 was change to 1 because you already have 5 numbers in the variable result.
You could test your count against a dictionary
import random
a = [2, 2, 3, 1, 2]
d = {idx: item for idx,item in enumerate(a, start = 1)}
l = []
while len(set(l) ^ set([*range(1, 6)])) > 0:
l = []
while len(l) != 6:
x = random.randint(1,5)
while l.count(x) == d[x]:
x = random.randint(1,5)
l.append(x)
print(l)

PYTHON: how to make a list with both chars and ints?

I currently have a file that's being read and making every line into a list. The file looks like this:
A 11 1
B 12 2
C 11 2
It's easy to make a list using split()
['A', '11', '1']
But how do I make a list that contains both chars and ints such that I get this below:
['A', 11, 1]
would be grateful for some help!
You can use the str.isdigit check as the conditional expression condition to get the digits to make ints:
[int(i) if i.isdigit() else i for i in line.split()]
As e.g. '-1'.isdigit() would returns False, we can use re to do string matching:
rcomp = re.compile(r'^[+-]?\d+$')
[int(i) if rcomp.search(i) else i for i in str_.split()]
e.g:
In [59]: str_ = 'A 2 3'
In [60]: [int(i) if i.isdigit() else i for i in str_.split()]
Out[60]: ['A', 2, 3]
In [61]: str_ = 'A -3 4 -8'
In [62]: [int(i) if rcomp.search(i) else i for i in str_.split()]
Out[62]: ['A', -3, 4, -8]

Convert a list of integers into a string with just one comma after x elements in Python

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!
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'
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))
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).
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"
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)])

Limiting number of input values in an array/list in Python

I'm obtaining input values in a list using the following statement:
ar = map(int, raw_input().split())
However, I would want to limit the number of inputs a user can give at a time. For instance, if the limit is specified by a number n, the array should only capture the first n values entered during the program.
e.g: if n = 6,
Input:
1 2 3 4 5 6 7 8 9 10
On performing 'print ar', it should display the following without any error messages:
[1, 2, 3, 4, 5, 6]
If you want to ignore the rest of the input, then you can use slicing to take only the first n input. Example -
n = 6
ar = map(int, raw_input().split(None, n)[:n])
We are also using the maxsplit option for str.split so that it only splits 6 times , and then takes the first 6 elements and converts them to int.
This is for a bit more performance. We can also do the simple - ar = map(int, raw_input().split())[:n] but it would be less performant than the above solution.
Demo -
>>> n = 6
>>> ar = map(int, raw_input().split(None, n)[:n])
1 2 3 4 5 6 7 8 9 0 1 2 3 4 6
>>> print ar
[1, 2, 3, 4, 5, 6]
How about indexing ar to just the 6th element? Technically, it's to the 7th element, as newarray will slice up to, but not including nth element
ar = map(int, raw_input().split())
print ar
#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
newarray=ar[0:6]
print newarray
#[1, 2, 3, 4, 5, 6]
This should allow for unlimited input
I was looking for a solution to the same question.
I figured out what I can do below is my solution.
bookid = []
M = int(input())
S = input().split()
for i in range(M):
books.append(S[i])
print(booksid)
But I think it's definitely not the most effective way to do it but easy.

Categories