Python - Printing 2 array elements for each line - python

I would like to create a (for) loop that print 2 Array elements for each line. You'll understand better with an example:
array = ["A","B","C","D"]
The output I want is:
A B
C D
How I can do this? Thanks!

There are some good posts earlier to learn more about Python looping of list. Here is a simple way to get what you expected output - regardless of this list has even or odd items.
lst = ['A', 'B', 'C', 'D'] # can add 'E' to try odd number items.
for i, ch in enumerate(lst, 1):
print(ch, end='\t')
if i % 2 == 0: # check to see if it hit the interval threshold?
print() # if you want 3 items in a row, you can change 2 to 3
Output
A B
C D

Iterate through the list and print 2 items with the print command. You can specify 2 as the increment for iterating, and join part of the list, and can handle odd numbers too. The slice of a list goes up to but not including the 2nd number, so slice with i:i+2. At the end of an odd-length list, there will be no 2nd item but the slice won't give an index-out-of-range error:
list1 = ["A","B","C","D","E"]
for i in range(0, len(list1), 2):
print(' '.join(list1[i:i+2]))
to get
A B
C D
E

Related

Can someone explain what the mylist[a][b] does in this Python code?

mylist = [ [2,4,1], [1,2,3], [2,3,5] ]
a=0
b=0
total = 0
while a <= 2:
while b < 2:
total += mylist[a][b]
b += 1
a += 1
b = 0
print (total)
I don't understand what mylist[a][b] does.
I tried adding print statements and checked each of the outputs, but I still can't figure out what it does.
The output with print statement I got was:
(each printed output every time it goes through the loop:)
2
4
1
2
2
3
(total)
14
I thought each output were the items inside the lists in mylist, but realized it's not. I also tried changing the numbers inside the lists, I still don't understand. Can someone simply explain it to me please?
The object between the [ and ] brackets is a "list" and a list can be made of other lists.
When you want to get the value from a list at a particular position, you use the [n] notation, where the n is the position (starting at zero).
If the object at position n is also a list, then you can extract items from that sub-list by again using the square brackets.
So, if I have a list l = [ [1,2,3], [4,5,6] ] then l[0] is equal to [1,2,3] and therefore l[0][1] is equal to 2.
The code you posted is looping over the lists inside the list and then the items inside each of those inner lists.
Okay, You can visualise this code mylist[a][b] as (mylist[a])[b]. So 1st part will get a value of position [a] from my list and then it will get a value of position [b] of mylist[a]. For an example:
mylist = [ [2,4,1], [1,2,3], [2,3,5] ]
Let's say a=1 , b=0
If you want to print mylist[a][b]. It will 1st get [1, 2, 3] then it will get the value at 0 position of the list. So the final output should be 1

How to find the index of an element in a list which is minimum in a sublist of that list in Python?

Assume I have a Python list:
x = [3,6,4,8,1,9]
and I want to find the index of the element in the list which is the minimum inside a sublist (say from index 2 to 4).
So I want to take a sublist x[2:5] and get the index of the minimum element (in this case x[4]).
How to return index 4 in such a case? If I use np.argmin() on the sublist, it will return the index according to the sublist (in this case, np.argmin(x[2:5]) will return 2 which is correct according to the sublist).
I don't want to use multiple if-else conditions. How to go about getting this index in a short way?
Just add the index where the sublist starts, and you'll have your original index:
x = [3,6,4,8,1,9]
subl_start = 2
subl_end = 5
ind_min = np.argmin(x[subl_start: subl_end]) + subl_start
You can also find the minimum of numbers between a threshold:
>>> x = [3,6,4,8,1,9]
>>> start, end = 2, 5
>>> min((e, i) for i, e in enumerate(x) if start <= i < end)[1]
4
Or incrementing the final result index:
>>> min((e, i) for i, e in enumerate(x[start:end]))[1] + start
4
I think this one liner will do fine for your case.
x.index(min(x[2:5]))
you can replace 2 & 5 with some variables also. (for index n to m -> (arr[n:m+1]))

How to get the number of the list in a list in Python 3?

I am trying to get the number of the nested list that contains the particular number. This is my code:
listo = [[1,2],[3,4,5]]
for x in listo:
if 3 in x:
print(len(x))
What I am trying to get here is the number of the nested list that has 3 in it. My code is returning 3 because I am of the function len, which is only returning the number of items inside the nested list that has the number. The output should be:
2
Since the number 3 is located on the second nested list. The count starts from 1, not 0.
How can I get the proper output?
Use enumerate:
listo = [[1,2], [3,4,5]]
res = next(i for i, sublist in enumerate(listo) if 3 in sublist)
print(res) # -> 1
Note that Python is 0-index languange; the first element on a list has index number 0. That is why the code above returns 1. If you want to get 2, well, just add 1 to that or, ever better, use the optional start parameter of enumerate (enumerate(listo, 1)).
To make the above Error-proof1, you can specify a default value to be returned in case 3 is not on any sublist.
res = next((i for i, sublist in enumerate(listo) if 3 in sublist), 'N\A')
1 next raises StopIteration if it exhausts the iterable without finding something to return, unless a default value is provided.
Use enumerate specifying the start value as 1:
listo = [[1,2],[3,4,5]]
for i, x in enumerate(listo, 1):
if 3 in x:
print(i)
# 2
Use enumerate so as to get the index of the element in the array.
l1 = ["eat","sleep","repeat"]
# printing the tuples in object directly
for ele in enumerate(l1):
print ele
Output:
(0, 'eat')
(1, 'sleep')
(2, 'repeat')
The same can be used for the code above.
listo = [[1,2,3],[4,5]]
for ind,x in enumerate(listo):
if 3 in x:
print(ind)
You can use enumerate. But if you are very new to coding this simple code is good.
Keep an extra variable (count) which will keep track of the index of the current list.
listo = [[1,2],[3,4,5]]
count = 0
for x in listo:
count += 1
if 3 in x:
print(count)
Simply use enumerate(). enumerate() returns a (element count, element) pair:
for count, element in enumerate(listo):
if 3 in element:
print(count + 1)
# Account for one-based indexing

Input in a cycle (Python)

I'm learning Python as my first language and now I trying to resolve this problem:
I have to make a loop where I ask the user which elements from a list they want to remove and then remove the elements selected. The loop stops only when the user insert a specific number that corresponds to the length of the list increased by 1 (so I won't have any problem).
I have another problem related to this:
elements_list = ['a','b','c','d']
length_list = len(elements_list)
for i in range(0, length_list):
print (str(i) + str(')') + elements_list[i])
This will print the list starting with 0:
0) a
1) b
2) c
3) d
What do I have to do if I want the list start with 1? (if I use 1 instead of 0 in the range it doesn't print the first element of the list)
In Python, lists can be iterated directly, and enumerate is used to generate indexes. Its optional second parameter gives a starting number:
>>> elements = ['a','b','c','d']
>>> for i,v in enumerate(elements,1):
... print('{}) {}'.format(i,v))
...
1) a
2) b
3) c
4) d
If using Python 3.6+, formatting output is even more simple using f-strings:
>>> elements = ['a','b','c','d']
>>> for i,v in enumerate(elements,1):
... print(f'{i}) {v}')
...
1) a
2) b
3) c
4) d
Refs:
enumerate
str.format
Formatted string literals
One way would be to add a 1 in the range, then subtract a 1 from the index
elements_list=['a','b','c','d']
lenght_list=len(elements_list)
for i in range(1, lenght_list+1):
print (str(i) + str(')') + elements_list[i-1])
Edit: TheoretiCAL's approach is even more straight forward, simply adding 1 to the print statement achieves the same thing.

Mistake in Python code

There is an array of integers. There are also disjoint sets, A and B, each containing integers. You like all the integers in set A and dislike all the integers in set B. Your initial happiness is 0. For each integer in the array, if i in A, you add 1 to your happiness. If i in B, you add -1 to your happiness. Otherwise, your happiness does not change. Output your final happiness at the end.
Input Format
The first line contains integers n and m separated by a space.
The second line contains n integers, the elements of the array.
The third and fourth lines contain m integers, A and B respectively.
Output Format
Output a single integer, your total happiness.
Sample Input
3 2
1 5 3
3 1
5 7
Sample Output
1
Can someone please explain what is wrong with this solution? It passes some test, but fails on others.
input()
array = set(input().split())
set1 = set(input().split())
set2 = set(input().split())
res = len(set1 & array) - len(set2 & array)
print(res)
The problem is that you're transforming your inputs to sets, which in turn removes the duplicates. If you have repeated values in your input, with the set you're only adding/substracting 1 to the resulting happiness. If that's correct, your code is fine. If not, then you should work with lists rather than sets.
The code could be something like this:
# The first part should stay the same, without the set() call on array
input()
array = input().split()
list1 = set(input().split())
list2 = set(input().split())
# Now we use some list comprehension to get the happiness result
res = sum([1 for elem in array if elem in list1]) - sum([1 for elem in array if elem in list2])
The first sum accumulates the positive points, and the second one the negatives. It works with multiple occurences, adding/substracting one point per each.
EDIT
A more clear approach, to understand the for loop
# The first part should stay the same, without the set() call on array
input()
array = input().split()
list1 = set(input().split())
list2 = set(input().split())
# We create a variable res which will store the resulting happiness, initially 0
res = 0
# Now we iterate through the elements in array and check wheter they should add or substract
for elem in array:
# If the element is in list1, we add 1 to res
if elem in list1:
res += 1
# If the element is in list2, we substract 1 from res
elif elem in list2:
res -= 1
I took the inputs for list A and B and as a general list. I wanted to obtain happiness in 1 line using list comprehension as below. After I merged print and "happiness =" , in one line. Apparently, this is the solution to make the code faster.
input()
my_array = input().split()
listA=list(input().split())
listB=list(input().split())
print (sum(1 for data in my_array if data in listA)+sum(-1 for data in my_array if data in listB))

Categories

Resources