I'm Trying to figure out how this works. Example One:
n = ["1ab", "2an", "3bca", "4adc"]
l = ["1", "2", "3"]
for m in n:
if "a" in m:
for k in l:
if k in m:
print k
1
2
3
Now I will try to print last member of n list.
n = ["1ab", "2an", "3bca", "4adc"]
l = ["1", "2", "3"]
for m in n:
if "a" in m:
for k in l:
if not k in m:
print k
2
3
1
3
1
2
1
2
3
I need to print a list member which does not contain any number listed in l variable but contains "a" in it.
-
2Please explain a bit more what you are trying to doJoucks– Joucks2013年11月05日 18:44:54 +00:00Commented Nov 5, 2013 at 18:44
-
I need to print a list member which does not contain any number listed in l variable but contains "a" in it.IKA– IKA2013年11月05日 18:52:43 +00:00Commented Nov 5, 2013 at 18:52
-
Then you should edit your questionJoucks– Joucks2013年11月05日 19:11:58 +00:00Commented Nov 5, 2013 at 19:11
4 Answers 4
Since 4 is not in your list l
, you cannot print it.
3 Comments
n = ["1ab", "2an", "3bca", "4adc"]
l = ["1", "2", "3"]
for m in n:
if "a" in m:
if not any([k in m for k in l]):
print m
4adc
Comments
The answer is in your second to last line. For every loop through n you loop through l and there are three members of n that meet if not k in m: condition. So
Loop 1 prints: 2,3 Loop 2 prints: 1,3 Loop 3 prints: 1,2 Loop 4 prints: 1,2,3
Comments
>>> l
['1', '2', '3']
>>> n
['1ab', '2an', '3bca', '4adc']
for el in n:
if(el[0] not in l):
print(el)
4adc
Or if you just want to print 4, based on your list sequence:
for el in n:
if(el[0] not in l):
print(el[0])
Now you just added to your question, "but contains "a"", add second iff.
for el in n:
if(el[0] not in l):
if('a' in el):
print(el[0],el)