This question already has answers here:
How to extract the n-th elements from a list of tuples
(8 answers)
Closed 4 years ago.
Am trying to print elements of index 1 like 4994 2993 100 20.5 from my tuple but it print ('dan', '2993').
b = (("ben","4994"),("dan","2993"),("Hans",100),("Frank",20.5))
print(b[1])
Have searched on this site and none of the answer provided gives me clue to solve this.
You can use unpacking in a list comprehension:
b = (("ben","4994"),("dan","2993"),("Hans",100),("Frank",20.5))
new_b = [i for _, i in b]
Output:
['4994', '2993', 100, 20.5]
Another list comprehension way:
b = (("ben","4994"),("dan","2993"),("Hans",100),("Frank",20.5))
new_b = [i[1] for i in b]
# ['4994', '2993', 100, 20.5]
b = (("ben","4994"),("dan","2993"),("Hans",100),("Frank",20.5))
for item in b:
print(item[1])
In this case you are trying to access the second element of a two-items tuple. Using slicing would be:
>>> b[0][1]
and you will get as output>
>>> '4994'
If you put this tuple into a for loop, the first element (item in my code) would be: ("ben","4994") and when you print(item[1]) you are having access to the second level of slicing, that is: '4994' in the first running of the loop and so on.
Related
This question already has answers here:
How to check if a tuple contains an element in Python?
(4 answers)
Closed 18 days ago.
how do i find a certain element in a tuple and print out the index of the element.
a = (1,2,3,4)
b = int(input('enter the element you want to find'))
if b in a :
print('found')
here is the simple program. now how do print the index of the element whic needs to be searched
Use .index:
if b in a:
print(a.index(b))
You can use enumerate as well:
enumerate
a = (1,2,3,4)
b = int(input('enter the element you want to find'))
for x,y in enumerate(a):
if b == y:
print(x)
Edit:
to find the multiple indices of an element:
Suppose we have b at 3 positions, now if you want to find all the three indices then:
a = (1,2,3,4,5,6,2,8,2)
b = 2
for i, x in enumerate(a):
if x == b:
print(i)
1
6
8
with list comprehension :
[i for i, x in enumerate(a) if x == b]
#[1, 6, 8]
Use:
print(a.index(b))
Use this link for working with tuples
This question already has answers here:
What is the id( ) function used for?
(13 answers)
Closed 2 years ago.
I knew when python's list append element,the element is appended to tail. I tried to output the element of the list, why the element's address is out of order? Please help me out,thanks!
list = []
list.append(2)
list.append(10)
list.append(3)
print('--append--')
for i in list:
print('i:{}, id:{}'.format(i,id(i)))
the output is:
--append--
i:2, id:140711739437936
i:10, id:140711739438192
i:3, id:140711739437968
The id() function returns a unique id for the specified object.
You need to use the index of the list
list = []
list.append(2)
list.append(10)
list.append(3)
print('--append--')
for i in list:
print('i:{}, id:{}'.format(i,list.index(i))) # replace id with list.index
id() returns identity (unique integer) of an object...
a=3
print(id(3)) #9752224
You can use this
list = []
list.append(2)
list.append(10)
list.append(3)
print('--append--')
for i in enumerate(list): #enumerate return an enumerate object.if list it [(0,2),(1,10),(2,3)]
print('i:{}, id:{}'.format(i[1],i[0]))# for getting index number i[0]
The id function is rarely used in actual programming, and usually, you use the list index to deal with lists. Your example will look something like:
mylist = []
mylist.append(2)
mylist.append(10)
mylist.append(3)
print(mylist)
Output:
[2,10, 3]
Sample code:
for x in range(len(mylist)):
print(x, mylist[x])
Output:
0, 2
1, 10
2, 3
You may check one of the good python tutorials on the web such as the one on the python web page: https://docs.python.org/3/tutorial/
This question already has answers here:
Subtracting 2 lists in Python
(16 answers)
Closed 3 years ago.
I have the following two list of lists and I want to substract every item from a from the corresponding item in b:
a = [[8.5], [9.3], [8.2]]
b = [[7.4], [2.3], [3.4]]
So the output should be
c = [[1.1], [7], [4.8]]
It seems to be very simple, but I am struggling with it. Does somebody have a solution?
Create flat list of both first
flat_list = [item for sublist in a for item in sublist]
then convert to numpy array
a= np.array(a)
b = np.array(b)
then make list of lists [i for i in a] and similarly b
This question already has answers here:
Remove all the elements that occur in one list from another
(13 answers)
Compute list difference [duplicate]
(17 answers)
Closed 6 years ago.
I have something like:
a = [4,3,1,6,3,5,3]
b = [4,2,6]
and I wanted to remove the 3 elements of b from a. I was trying to do:
c = a - b
but I was thinking that the inverse of merge (+) might not be a thing, and was correct: Unsupported Operand types for -: list and list. I was contemplating just looping over them, but that just doesnt really sound pythony.
My end state is going to be: c = [3,1,3,5,3]
If you had not noticed, b is not a subset of a and these are unordered. 2 different sets, these sets are not unique either, but only want to remove 1 instance per i in b, not all instance of i in b
EDIT It seems that the current answer does not resolve my question.
a = [1,1,2,2,2,3,4,5]
b = [1,3]
c = [x for x in a if x not in b]
#c result is [2,2,2,4,5]
I want c to return: [1,2,2,2,4,5]
For the sake of speed typing, I just put sorted numbers, but the lists ARE IN FACT unsorted, though for the sake of cleanliness we can sort them.
They are just unsorted at init. Since there are duplicates in list items, I can't use a set as per the definition of set.
You can use the following code:
[x for x in a if x not in b]
As input and output lists are unordered, use Counter is a way to go:
from collections import Counter
a = [4,3,1,6,3,5,3]
b = [4,2,6]
c = list((Counter(a) - Counter(b)).elements())
print(c)
This solution handles the following case differently than ysearka answer:
a = [4,3,1,6,3,5,3]
b = [3]
Where many answers here leads to c = [4,1,6,5], the one using Counter will outputs c = [4,1,6,3,3,5].
This behavior is also implemented by DAXaholic answer, but with modification of an existing list, which is not a pythonic way to go, and could be costly on big lists.
As you noted you only want to remove the items once per occurrence:
for x in [tmp for tmp in b if tmp in a]:
a.remove(x)
for x in b:
while x in a:
a.remove(x)
Now a is
[3, 1, 3, 5, 3]
This question already has answers here:
How can I make the efficent for loop in Python?
(3 answers)
Closed 9 years ago.
I have the loop like this
for a in list1:
for b in list2:
for c in list3:
print "Hello"
Without using any if else statement. i want that if there are elements in all list then it should repeat as normal but if the list is empty then for loop should behave like its don't exist and runs the code below it once
like if list3 is empty and list2 contains 2 elements and list1 has one element then i should see hello 2 times
for a in list1 or [None]:
for b in list2 or [None]:
for c in list3 or [None]:
print "Hello"
The None in [None] can be replaced by any other single object.
This way the empty list will be replaced by a list with one element and the loop will proceed once.
Other way (if the variables a, b and c are not important) would be:
for i in xrange(max(len(list1), 1) * max(len(list2), 1) * max(len(list2), 1))):
print 'Hello'
UPDATE
Your idea of using my code without adapting it correctly:
for m,n in zip(l1,l2) or [None]:
can be corrected using:
for m,n in zip(l1 or [None], l2 or [None]):
or
for m,n in zip(l1, l2) or [[None, None]]: