Storing list of lists in matrix format [duplicate] - python

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.

Related

Python input array one line

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.

Getting an extra row of Nones when trying to flatten a list of lists with map or list comprehensions , why?

lol = [[7, 1, 0], [10, 2, 5], [6, 5, 9], [9, 9, 9], [1, 23, 12]]
when I try to flatten it using maps and list comprehensions and try to print it out in separate lines I get one extra row at the end containing Nones , why ?
Option 1 : >>> list(map(lambda x : print(x),[' '.join(map(str,triples)) for triples in lol]))
Option 2 : >>> list(map(lambda x : print(x) , list(map(lambda x : ' '.join(map(str,x)),lol))))
The output I am getting in both cases is :
7 1 0
10 2 5
6 5 9
9 9 9
1 23 12
[None, None, None, None, None]
why the extra row of 'None's at the end ?
It's not something that you are printing but something that you are storing.
You first print all the elements and then you are storing the output of the print statement which is None
for triples in lol: print(' '.join(map(str,triples))) # if you just want to print
lolz = [' '.join(map(str,triples)) for triples in lol] # if you just want to store
print(lolz)

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)])

Split string of digits into lists of even and odd integers

Having such code
numbers = '1 2 3 4 5 6 7 8'
nums = {'evens': [], 'odds': []}
for number in numbers.split(' '):
if int(number) % 2:
nums['odds'].append(number)
else:
nums['evens'].append(number)
How can accomplish same on fewer lines?
Short code is not better code. Short code is not faster code. Short code is not maintainable code. Now, that said, it is good to make your individual components concise and simple.
Here's what I would do:
def split_odd_even(number_list):
return {
'odds': filter(lambda n: (n % 2) != 0, number_list),
'evens': filter(lambda n: (n % 2) == 0, number_list)
}
def string_to_ints(string):
return map(int, numbers.strip().split())
numbers = '1 2 3 4 5 6 7 8 9 10'
nums = split_odd_even(string_to_ints(numbers))
print nums
This gives me:
{'odds': [1, 3, 5, 7, 9], 'evens': [2, 4, 6, 8, 10]}
While this code has actually added a few lines in length, it has become much more clear what the program is doing, as we've applied Abstraction and made each component of the code do only one thing well.
Even though we've added two functions, the most-visible part of the code has gone from this:
numbers = '1 2 3 4 5 6 7 8'
nums = {'evens': [], 'odds': []}
for number in numbers.split(' '):
if int(number) % 2:
nums['odds'].append(number)
else:
nums['evens'].append(number)
To this:
numbers = '1 2 3 4 5 6 7 8 9 10'
nums = split_odd_even(string_to_ints(numbers))
And just by reading these two lines, we know that numbers is converted from a string to a list of ints, and that we then split those numbers into odd and even, and assign the result to nums.
To explain a a couple of things that may not be familiar to all:
map() calls a function for every item in a list (or tuple or other iterable), and returns a new list with the result of the function being called on each item. In this case, we use it to call int() on each item in the list.
filter() calls a function for every item in a list (or tuple or other iterable), which returns True or False for each item (well, truthy or falsey), and returns a list of items that evaluated to True when the function is called.
Lambda Expressions (lambda) are like "mini-functions" that take arguments and can be created in-place.
A functional aproach:
>>> numbers = '1 2 3 4 5 6 7 8'
>>> numbers = map(int, numbers.split())
>>> nums = {'evens': filter(lambda x: x%2 == 0, numbers), 'odds': filter(lambda x: x%2 != 0, numbers)}
>>> nums
{'evens': [2, 4, 6, 8], 'odds': [1, 3, 5, 7]}
You can accomplish the same results with itertools.groupby, like so:
>>> from itertools import groupby
>>>
>>> numbers = '1 2 3 4 5 6 7 8'
>>> d = {'even':[], 'odd':[]}
>>> mynum = [int(x) for x in numbers.strip().split()]
>>> for k,g in groupby(mynum, lambda x: x % 2):
if k:
d['odd'].extend(g)
else:
d['even'].extend(g)
>>> d
{'even': [2, 4, 6, 8], 'odd': [1, 3, 5, 7]}
numbers = '1 2 3 4 5 6 7 8'
nums = {}
nums["even"] = [int(i) for i in numbers.split() if int(i) % 2 == 0]
nums["odd"] = [int(i) for i in numbers.split() if int(i) % 2 == 1]
print(nums)
Output:
{'even': [2, 4, 6, 8], 'odd': [1, 3, 5, 7]}
If you just want to try it out:
numbers = '1 2 3 4 5 6 7 8'
nums = {'evens': [], 'odds': []}
for number in numbers.split(' '):
category = 'odds' if int(number) % 2 else 'evens'
nums[category].append(number)
But if you want to use it in production: Readable code is more important than 'short' code
You can do it as a one-liner, but I wouldn't recommend it. Your code is perfectly fine.
[nums['odds'].append(n) if int(n)%2 else nums['evens'].append(n) for n in numbers.split(' ')]

Updating list values with new values read - Python [duplicate]

This question already has answers here:
How do i add two lists' elements into one list?
(4 answers)
Closed 9 years ago.
I was't really sure how to ask this. I have a list of 3 values initially set to zero. Then I read 3 values in at a time from the user and I want to update the 3 values in the list with the new ones I read.
cordlist = [0]*3
Input:
3 4 5
I want list to now look like:
[3, 4, 5]
Input:
2 3 -6
List should now be
[5, 7, -1]
How do I go about accomplishing this? This is what I have:
cordlist += ([int(g) for g in raw_input().split()] for i in xrange(n))
but that just adds a new list, and doesn't really update the values in the previous list
In [17]: import numpy as np
In [18]: lst=np.array([0]*3)
In [19]: lst+=np.array([int(g) for g in raw_input().split()])
3 4 5
In [20]: lst
Out[20]: array([3, 4, 5])
In [21]: lst+=np.array([int(g) for g in raw_input().split()])
2 3 -6
In [22]: lst
Out[22]: array([ 5, 7, -1])
I would do something like this:
cordlist = [0, 0, 0]
for i in xrange(n):
cordlist = map(sum, zip(cordlist, map(int, raw_input().split())))
Breakdown:
map(int, raw_input().split()) is equivalent to [int(i) for i in raw_input().split()]
zip basically takes a number a lists, and returns a list of tuples containing the elements that are in the same index. See the docs for more information.
map, as I explained earlier, applies a function to each of the elements in an iterable, and returns a list. See the docs for more information.
cordlist = [v1+int(v2) for v1, v2 in zip(cordlist, raw_input().split())]
tested like that:
l1 = [1,2,3]
l2 = [2,3,4]
print [v1+v2 for v1, v2 in zip(l1, l2)]
result: [3, 5, 7]
I would go that way using itertools.zip_longest:
from itertools import zip_longest
def add_lists(l1, l2):
return [int(i)+int(j) for i, j in zip_longest(l1, l2, fillvalue=0)]
result = []
while True:
l = input().split()
print('result = ', add_lists(result, l))
Output:
>>> 1 2 3
result = [1, 2, 3]
>>> 3 4 5
result = [4, 6, 8]
More compact version of #namit's numpy solution
>>> import numpy as np
>>> lst = np.zeros(3, dtype=int)
>>> for i in range(2):
lst += np.fromstring(raw_input(), dtype=int, sep=' ')
3 4 5
2 3 -6
>>> lst
array([ 5, 7, -1])

Categories