This question already has answers here:
How can I iterate over overlapping (current, next) pairs of values from a list?
(12 answers)
Closed 6 years ago.
if given a command like:
python 1.py ab 2 34
How to print the next argument while you are currently sitting on the one before. e.g if x is ab then I want to print 2:
import sys
for x in sys.argv[1:]:
print next element after x
I am unsure what you want to print but this syntactic sugar can help:
for x in sys.argv[1::2]:
print x
This prints every other element. So this will return ab 34
for x in sys.argv[2::2]:
print x
This will return 2
The number after the :: is how many slots in the array.
Edit:
To answer your specific question:
val = 1
for index, x in enumerate(sys.argv[1::2]):
val += 1
print sys.argv[index+val]
The index increases by 1 each time, and the val by 1 too, meaning every loop we skip 2 variables. Hence for something like python yourcode.py a 1 b 2 c 3 d 4 output will be 1 2 3 4
Related
This question already has answers here:
What does enumerate() mean?
(7 answers)
Closed 12 months ago.
list = []
word = 'hello'
for i in word:
list.append(i)
for i in list:
print(list.index(i))
output:
0 1 2 2 4
I dont know how to make the second 'l' to have an index of 3 instead of 2. rindex() does not work on for the code that I am making
Since you're printing just the list indexes which (by definition) are 0 1 2 3 4, you could use a simple range() loop:
for i in range(len(mylist)):
print(i)
The index() method returns the position at the first occurrence of the specified value.
To have the index of all the elements you can do like this
_list = []
word = 'hello'
for i in word:
_list.append(i)
for i in range(len(_list)):
print(_list[i], _list.index(_list[i], i))
This question already has answers here:
How can I iterate over overlapping (current, next) pairs of values from a list?
(12 answers)
Closed 2 years ago.
If I have a loop for example:
for i in nums:
print(i) #print current item
print(NEXT ITEM IN LIST FROM CURRENT POS)
How would I get it to print the current item and then the next item relevant to the current item?
I want it to print every first item + the next item
so a list of nums 1 2 3 4 5 would print:
1
2
3
4
5
not
1
2
2
3
3
4
4
5
5
I hope it makes sense
You can use enumerate:
for idx, i in enumerate(nums):
print(i) # print current item
if idx < len(nums) - 1: # check if index is out of bounds
print(nums[idx+1])
Concerning your follow up question on how to handle two elements per list iteration, without repeating any elements, you can use range with a step of 2, e.g.
for idx in range(0, len(nums), 2):
print(nums[idx])
if idx < len(nums) - 1:
print(nums[idx+1])
You can zip through your list:
for x, y in zip(nums, nums[1:]):
print(x, y, sep='\n')
you should use print(num[I]) for the current item and print(num[I+1]) for the next. but make sure to not access the next element when I is the length of the list.
You should use enumerate function
Find your answer here. There is already similar post for the mentioned issue.
This question already has answers here:
Python, Make an iterative function into a recursive function
(4 answers)
Count to zero then Count up
(2 answers)
Closed 3 years ago.
I want to define a function as f(a,b) such that it generates a series as:
10,8,6,4,2,0,2,4,6,8,10 if a=10 and b=2 using Recursion.
def pattern(a,b):
if a-b < 0:
print(a)
return pattern(a+b,b)
print(a)
else:
print(a)
return pattern(a-b,b)
The result I get is
10
8
6
4
2
0
2
0
2
0
..... infinity
... but this is wrong.
You just need to use recursion
from __future__ import print_function
def psearch(a,b):
if a > 0:
print(a,end = ',')
psearch(a - b,b)
print(',',end="")
print(a,end = "")
else:
print(a,end="")
psearch(12,5)
print()
OUTPUT
12,7,2,-3,2,7,12
This question already has answers here:
Check if all elements in a list are identical
(30 answers)
Closed 4 years ago.
I'm scraping with python and I have a list made at most of two letters(R and D), where the content can be always the same (i.e. all the elements are R or alternatively D) or it can be that there are some D and some R. How can I get 1 if the list is made of either R only (or D only) and 0 if there are both D and R? Thanks in advance
You can just check to see if all the elements are identical.
val = 1 if all(elem == items[0] for elem in items) else 0
This question already has answers here:
How do I get the number of elements in a list (length of a list) in Python?
(11 answers)
Closed 3 months ago.
I am receiving the count of each line in each list,
I am looking to sum each particular values of entire list, (Nested lists included)
[[3],[4],][1],[3]] = * 11 is my desired result.
example: code
ar1 = [
['jam','apple','pear'],
['toes','tail','pinky','liar'],
['aha!'],
['jam','apple','pear']
]
def function(arg1)
heads = 0
for i in arg1:
heads += arg1.count(i)
print heads
I have used this print because i dont know how to compile and debug any other for than the print statement and recheck work, so please no flaming.(newbie alert)
example: result
['jam','apple','pear'] 1
['toes','tail','pinky','liar'] 2
['aha!'] 3
['jam','apple','pear'] 4
I prefer a hint, or hints to what methods i should be applying or an example. I am in no way expecting a solution. I
You have some choices :
1.flatten your nested list and calculate the length of total list:
>>> len(reduce(lambda x,y:x+y,ar1))
11
Or you can loop over your list and sum the length of all your sub-lists you can do it with a generator expression within sum function :
>>> sum(len(i) for i in ar1)
11
In case your actual data contains deeper nesting than you've shown:
def sum_len(lst):
return sum(1 if not isinstance(e, list) else sum_len(e) for e in lst)
ar1 = [
['jam','apple','pear'],
['toes','tail','pinky','liar'],
['aha!'],
['jam','apple','pear']
]
print sum_len(ar1) # 11
# Same elements, with arbitrary list wrapping:
ar2 = [
[['jam','apple',['pear']]],
[['toes',['tail','pinky'],'liar']],
[['aha!']],
[[['jam','apple'],'pear']]
]
print sum_len(ar2) # 11