iterating to nth value in python - python

How I will iterate for loop in python for 1 to specific value?
I can iterate on list in python like :
for x in l:
print x
But.
If i wanted to iterate from 1 to number th, in matlab I will do :
str = "abcd"
for i=1:z
for j=1:y
if s(:,i)==s(j,:)'
Seq(i)=str(j);
end
end
end
How I will iterate such in python?

for i in range(0, 11):
print i
HTH

To access values in lists, use the square brackets for slicing along with the index.
for x in l[start:end]:
print x
You have a grate post here about slice notation
Another grate link about lists
Example 1:
myList = [1, 2, 3, 4]
for x in myList[:-1]:
print x
Output:
1
2
3
Example 2:
myList = [1, 2, 3, 4]
for x in myList[1:3]:
print x
Output:
2
3

You need to get use to the idea of slicing in python, see Explain Python's slice notation
Non-slicing:
a = [1,2,3,4,5,6,7,8]
n = 5
for i in range(n):
print a[i]
With slices:
a = [1,2,3,4,5,6,7,8]
n = 5
print a[:n]

Use slice notation (This creates temporary list that contains first n items):
>>> s = "abcd"
>>> for x in s[:2]:
... print(x)
...
a
b
or use itertools.islice:
>>> import itertools
>>> for x in itertools.islice(s, 2):
... print(x)
...
a
b

Related

Check for equal values in lists and set them to 0

I want the elements from list a to be zero in list b
a = [80,85,140,145]
b = list(range(200))
Is there a way to do it instead of writing it manually:
b[80]=0
b[140]=0
because I am running simulations and the values in list a and also the list length of a are always changing from one simulation to another and I would like to find a way to automatically set the values of list a to 0 in list b
Why not use a list comprehension to filter on creation:
b = [x if x not in a else 0 for x in range(200)]
The if x not in a checks the number isn't suppose to be filtered or not, if it's to be filtered the else 0 will set it to zero.
Why not just do a simple loop? Naive solution is to just do the following:
a = [8,5,1, 14]
b = list(range(20))
i = 0
while (i < len(a)):
b[a[i]] = 0
i = i+1
print(b)
If I understand the question correctly, this will replace the items in b with zero at the indices contained in a:
for i in a:
b[i] = 0
You can use a list comprehension for this.
c = [0 for x in b if x in a]
You can try this:
for i in b:
if i in a:
b[i]=0
Hope this helps :D
Simple list comprehension is good for this:
a = [2, 4]
b = list(range(10))
[x if x not in a else 0 for x in b]
## [0, 1, 0, 3, 0, 5, 6, 7, 8, 9]

Multiplying every second number in a list

I need to be able to multiply every second number in a list by 2 so say:
List = [1,2,3,4]
I want this to return [1,4,3,8] but all the ways that I have tried it such as
credit_card = [int(x) for x in input().split()]
credit_card[::2] = [x*2 for x in credit_card[::2]]
print(credit_card)
If i input the same list from before it returns [2,2,6,4]
Is there a way to accomplish what I'm trying to accomplish?
You are almost there, you just need to start from the second (1-indexed) element:
credit_card[1::2] = [x*2 for x in credit_card[1::2]]
That said, since you seem to be implementing the Lunh checksum, you only need a sum of those digits without having to update the original data, like done in this example.
lst = [1,2,3,4]
new_lst = [2*n if i%2 else n for i,n in enumerate(lst)] # => [1, 4, 3, 8]
credit_card = input().split()
for x in len(credit_card)
if x % 2 != 0
credit_card[x] = credit_card[x] * 2
print (credit_card)
for i,_ in enumerate(credit_card):
if i%2:
credit_card[i] *= 2
or if you want to be fancy:
credit_card=[credit_card[i]*(2**(i%2)) for i in range(len(credit_card))]
Another solution using enumerate:
[i* 2 if p % 2 else i for p, i in enumerate(l)]
where i is the p-th element of l.
>>> l = [1,2,3,4]
>>>
>>> list(map(lambda x: x*2 if l.index(x)%2 else x, l))
[1, 4, 3, 8]

sum function not working

I am trying to write a program that sums the integers in the odd columns of a list
def sum_of_odd_cols(x):
for j in range(len(x)):
odds=[x[k][j] for k in range(len(x)) if j%2!=0]
return sum(odds)
x=[[1,2,5],[3,4,6],[7,8,9]]
print(sum_of_odd_cols(x))
What I get from this is '0', why is this happening?
Also one more question
x=[[1,2,5],[3,4,6],[7,8,9]]
for j in range(len(x)):
col=[column[j] for column in x]
this also seems to create a list of the columns in list x, however I don't understand how this works
is 'column' a built in function in python?
How about:
def sum_of_odd_cols(x):
oddsum = 0
for j in range(len(x)):
oddsum += sum([x[k][j] for k in range(len(x)) if j%2!=0])
return oddsum
x=[[1,2,5],[3,4,6],[7,8,9]]
print(sum_of_odd_cols(x))
This probably isn't the best way of doing it, but it will get your code working. The odds variable was getting overwritten by a new list in each iteration of the loop, and since the final column was empty (it's index is even), the sum was always 0.
The reason it returns 0 is because your odds array is empty at the end of the for loop; because in each iteration of the loop you are resetting odds. If you write your loop the 'long' way, it will return the correct results:
odds = []
for j in range(len(x)):
for k in range(len(x)):
if j % 2 != 0:
odds.append(x[k][j])
If I add some print statements, this is what happens:
j is: 0
k is: 0
k is: 1
k is: 2
j is: 1
k is: 0
Adding: 2 to odds
k is: 1
Adding: 4 to odds
k is: 2
Adding: 8 to odds
j is: 2
k is: 0
k is: 1
k is: 2
>>> odds
[2, 4, 8]
For the second part of your question:
Also one more question
x=[[1,2,5],[3,4,6],[7,8,9]] for j in range(len(x)):
col=[column[j] for column in x]
this also seems to create a list of the columns in list x, however I
don't understand how this works is 'column' a built in function in
python?
No, this is a list comprehension, a short-hand way of constructing lists.
The loop is actually:
col = []
for column in x:
col.append(column[j])
Where j is some other variable (set above the comprehension).
If you are comfortable with NumPy:
import numpy as np
a = np.array([[1,2,3], [1,2,3]])
b = np.sum(a[:,::2], axis=0) # column 0, 2, ...
# b = [2, 6]
b = np.sum(a[:,::2])
# b = 8
c = np.sum(a[:,1::2], axis=0) # column 1, 3, ...
You can do
x = [[1,2,5],[3,4,6],[7,8,9]] # Generate the list
sum([sum(k[1::2]) for k in x]) # Sum the numbers in odd columns
# 14
if you need the combined sum for all the numbers in the odd columns.
Your first question has been answered various times.
As for your second question, think about unzipping your nested list (supposing it is not ragged):
>>> x=[[1,2,5],[3,4,6],[7,8,9]]
>>> [x for x in zip(*x)]
[(1, 3, 7), (2, 4, 8), (5, 6, 9)]
This gives you a list containing the columns.
If the tuples are a problem and you need lists inside the list, use the builtin list:
>>> [list(x) for x in zip(*x)]
[[1, 3, 7], [2, 4, 8], [5, 6, 9]]
So basically your two questions boil down to this:
def sum_of_odd_cols(x):
return sum(sum(x[1::2]) for x in x)
def rows_to_columns(x):
return [list(x) for x in zip(*x)]

How to store a list of numbers generated as output in Python?

Suppose I want to add several numbers together like:
1. Find even numbers between 1-100.
2. Find odd numbers between 2-200.
3. Add them.
So for this, I can check for even numbers and odd numbers respectively, but to add them, they must be stored somewhere. Now how can I do this?
i.e. store the output of the first step, store the output of second step and then add them together.
Find even numbers between 1-100:
>>> l = [i for i in range(1,101) if i % 2 == 0]
>>> print l
[2, 4, 6, ..., 100]
Find odd numbers between 2-200:
>>> l2 = [i for i in range(2,200) if i % 2 != 0]
>>> print l2
[3, 5, 7, ..., 199]
Find the sum:
>>> total = sum(l) + sum(l2)
>>> print total
12540
What I've done is List Comprehensions, a loop which creates values for whatever factors you want. Here's a link to the documentation about it: http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions
Even Numbers List:
a = [i for i in range(2,101,2)]
Odd Numbers List:
b = [i for i in range(3,200,2)]
Sum:
c = sum(a) + sum(b)
This is what containers like lists are for:
numbers = [] # Setup an empty list
for number in range(10): # Loop over your numbers
numbers.append(number) # Append the number to your list
print sum(numbers) # 45
Results of first and second steps can be stored in 2 different lists.
list1 = [2, 4, 6 .. ]
list2 = [1, 3, 5 .. ]
Lists are documented on python docs at http://docs.python.org/2/tutorial/datastructures.html#more-on-lists
You don't really need a list.
>>> sum(x for x in range(1,100) if x % 2)
2500
>>> sum(x for x in range(2,200) if not x % 2)
9900

Python printing without commas

How can I print lists without brackets and commas?
I have a list of permutations like this:
[1, 2, 3]
[1, 3, 2] etc..
I want to print them like this: 1 2 3
blah = [ [1,2,3], [1,3,2] ]
for bla in blah:
print ' '.join(map(str, bla))
It's worth noting that map is a bit old-fashioned and is better written as either a generator or list-comp depending on requirements. This also has the advantage that it'll be portable across Python 2.x & 3.x as it'll generate a list on 2.x, while remain lazy on 3.x
So, the above would be written (using a generator expression) as:
for bla in blah:
print ' '.join(str(n) for n in bla)
Or using string formatting:
for bla in blah:
print '{} {} {}'.format(*bla)
If the list is
l=[1,2,3,4,5]
Printing the list without bracket and commas:
print " ".join(map(str,l))
#1 2 3 4 5
Number_list = [1, 2, 3, 4, 5]
Print(*Number_list, sep="") # empty quote
Example you have a list called names.
names = ["Sam", "Peter", "James", "Julian", "Ann"]
for name in range(len(names)):
print names[name],
In [1]: blah = [ [1,2,3], [1,3,2] ]
In [2]: for x in blah:
...: print x[0],x[1],x[2]
...:
1 2 3
1 3 2
In [3]:
n = int(input())
i = 1
x = []
while (i <= n):
x.append(i)
i = i+1
print(*x, sep='')
assuming n is a number input by a user, you can run through a loop and add the values i to n to a list x. at the end, you can print the array (*x) using nothing ('') to separate the values. this keeps your values in their original format, in this case a number.
You can do this.
Code:
list = [[1, 2, 3], [3, 2, 1]]
for item in list:
print("{}".format(item, end="\n")
Result:
[1, 2, 3]
[3, 2, 1]
completedWord=['s','o','m','e',' ','w','o','r','d','s']
print(*completedWords,sep=' ')
output = s o m e w o r d s
note there are two spaces in sep=' '
temp = [[2,3,5],[2,5,3]]
for each_temp in temp:
if isinstance(each_temp,list):
for nested_temp in each_temp:
print nested_temp

Categories

Resources