l = ['a1',1,'b1',2,'c1',3]
how to print like below(expected out)
a1 1
b1 2
c1 3
Do I need to do zip function for this? or any other way
Slice with a stride of 2 and zip with an offset slice:
l = ['a1',1,'b1',2,'c1',3]
for a, b in zip(l[::2], l[1::2]):
print(a, b)
A for loop would do the trick (as mentioned in other answers)
But a list comprehension will also work:
[print(str(x[0]) + ' ' + str(x[1])) for x in zip(l[0::2], l[1::2])]
How does this work?
l[0::2] takes every element from l, starting at index 0, until the last element, and with steps of 2 (in other words it takes all the even elements)
l[1::2] takes all the odd elements
zip bundles those into a zip object (iterable tuples) of pairs
the last step is iterating over those and executing the print function for each of them
A for loop will solve the problem:
l = ['a1',1,'b1',2,'c1',3]
for index in range(0, len(l), 2):
print(l[index] + " " + str(l[index+1]))
It starts at index 0 (at "a1") and goes in steps of 2 (jumping to "b1"). The print statement adds an offset of 1 to access the value in between.
Alternatives for the print statement itself, not changing the structure of the code:
print(l[index], str(l[index+1]), sep=" ") # use space as a separator
print(f"{l[index]} {str(l[index+1])}") # use f-string for formatting
For this i would recommend using dictionaries if its possible, i don't know what you are trying to do.
Use them like this:
l = {'a1':1,'b1':2,'c1':3}
for key, value in l.items():
print("{} {}".format(key, value))
Related
Okay so say I have a list of ranges like
a = [[167772352, 167772415], [167772160, 167772223], [167772288, 167772351], [167772224, 167772255]]
and then I have a number like
b = 167772241
Now I know that b is within the 4th item of the list but how would I check that b is within that in a optimal way? I've thought of using a for loop going through each number of the list and then inserting when the loop breaks but I feel like there has to be some python library function that could handle this? Any suggestion would be welcome!
Simply iterate over the list, take both values and create a range from those values and check if b in range(...), also use enumerate, start it from 1 and you will get in which consecutive range in the list the number is.
a = [[167772352, 167772415], [167772160, 167772223], [167772288, 167772351], [167772224, 167772255]]
b = 167772241
for index, (start, end) in enumerate(a, start=1):
if b in range(start, end + 1):
print(index)
break
You can also use a list comprehension:
a = [[167772352, 167772415], [167772160, 167772223], [167772288, 167772351], [167772224, 167772255]]
b = 167772241
index = [b in range(start, end + 1) for start, end in a].index(True) + 1
print(index)
Also note the end + 1 used in both ranges, that is because the range doesn't include its end value so adding 1 means that the range is inclusive on both sides. Also both methods will get the index that starts from one, which is how you would usually count (1, 2, 3, 4, ...) as you have stated in your question that b should be in the fourth range (which means that you started counting from 1)
You could use map in the following way:
a = [[167772352, 167772415], [167772160, 167772223], [167772288, 167772351], [167772224, 167772255]]
b = 167772241
c = list(map(lambda a_: b in range(a_[0], a_[1] + 1), a))
The output will be a list of booleans that will indicate whether b is contained in each of a's ranges:
out: [False, False, False, True]
map takes two arguments. The first is a function (or a lambda), that it will then apply to each element of the list that you pass as a second parameter. map returns an special object, but you can easily convert it into a list by using list().
You could write a regular function that will check if b is in range, but using a lambda allows you to write the expression in one line. It takes one argument, a_, which will be populated with each element of the list.
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
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.
I am trying to compare two lists for the same element at the same index. The idea is to verify whether both lists contain same element at the same index. If yes, I want to count such occurrences. Here is my code:
count = 0
a = ['.ps2\n >|<4 *|*.ps2xml', '.c\n >|<2 *|*.wsc', '.h\n >|<2 *|*.wsh', '.c\n >|<2 *|*.chm', '.h\n >|<2 *|*.hta' ]
b = ['.ps2xml', '.chm', '.hta']
for x in a:
for y in b:
if y==x[x.index(" *|*")+4:]:
print "match"
count += 1
print count
This gives me a count of 3. What I expect is 1 because only first element of b matched with a's first element. The second element of both lists differ. The third elements are also different. The remaining elements in list a should not count as there is no such index in b.
Hope it makes sense. Thanks
In that case, you should not use nested loops (since this means you will repeat the search over b for each line in a); but use a zip(..):
for x,y in zip(a,b):
if y==x[x.index(" *|*")+4:]:
print "match"
count += 1
print count
zip takes some iterators and generates tuples. In this case the i-th tuple is thus (a[i],b[i]) so to speak.
Short solution using min() function(to get a limit size of compared sequences):
for i in range(min([len(a), len(b)])):
if (a[i][a[i].index('*|*') + 3:] == b[i]):
count += 1
print(count)
The output:
1
does the match have to be qualified as following '*|*' ?
if not then really simple is:
sum([1 for e, f in zip(a, b) if f in e])
or in later versions of python where iterator args are automatically unpacked:
sum(f in e for e, f in zip(a, b)) # relies on bools True, False = ints 1, 0
if the match is just the last bit you could split
'.ps2\n >|<4 *|*.ps2xml'.split(" *|*")
Out[13]: ['.ps2\n >|<4', '.ps2xml']
'.ps2\n >|<4 *|*.ps2xml'.split(" *|*")[1]
Out[14]: '.ps2xml'
sum([1 for e, f in zip(a, b) if f in e.split(" *|*")[1]])
and while sum() is more "intentional" len() could be used for a speed advantage since it doesn't have to iterate over the list
File
sims 10 500
dettol 45 200
nims 200 540
Code:
for E, w in vb, T.readline():
name, qty, price = w.split()
print("you bought" + str(vb[E]) + "from" + name)
Description
I want to run two loop together, one for a file and one for an array. Also, the expected output for each iteration would be
>>> "you bought 1 from nims"
if "nims" has 1 quantity.
I used like to do
for i, k in j, T.readline:
but it's not working.
You haven't clarified what vb is, but I don't think that loop is doing what you think it does. First, here's what it looks like to the interpreter:
for E, w in (vb, T.readline()):
This isn't going to take each element of vb and each line of T. Instead, it's going to take vb and attempt to unpack it to E and w, and then do the same thing for T.readline() on the second iteration. For example:
>>> a = (1, 2)
>>> b = (5, 6)
>>> for i, j in a, b: print(i, j)
1 2
3 4
Notice that it doesn't print the 0th element of a and b, but both elements of a followed by both elements of b. If you wanted to combine them you would use zip:
>>> for i, j in zip(a, b): print(i, j)
1 3
2 4
Finally, T.readline() the way you are using it is not going to give you each line of T. Rather, it's going to take the first line in T (assuming you don't read other lines prior to the loop) and iterate over the characters of that line.
You are probably looking for zip:
with open("test") as T:
vb = [1, 2, 3]
for E, w in zip(vb, T):
name, qty, price = w.split()
print("you bought {} from {}".format(E, name))
Also note that there were two other errors in your code:
you want to iterate all the lines in the file T, not the letters in the first T.readline()
E is already the element from the list, not the index of that element
Note that in Python 2.x, zip will consume the entire file at once, so it that file is very large, you probably want to use itertools.izip instead, which creates an iterator. In Python 3.x, zip itself is an iterator.
In addition to paidhima's asnwer, you could maybe consider using enumerate() such as
for i,line in enumerate(T):
print i, line
assuming that T is the name of your file. This would print
0 sims 10 500
1 dettol 45 200
2 nims 200 540
Is this what you want?