how to find a particular key in output of python - python

I have a python function rows which output as:
(
[u'ABC'],
[u'DEF'],
[u'GHI']
)
I want to search DEF in this and print("Hello")
I did this:
for i in rows[]:
if i == "DEF":
print("Hello")
But this is not working. Can someone please guide

rows = ( [u'ABC'], [u'DEF'], [u'GHI'])
print rows
for i in rows:
print i
if i == [u"DEF"]:
print("Hello")
if i[0] == u"DEF":
print "world"
I do not know, what exactly is your problem.
The string is inside a list. Either you compare the complete list with a list of this string or the first element of the list with the string itself.

Related

I have to use "IN Operator" but can't use"True" in the codes to get "True" as an answer

I had to modify the code in such a way that I use "In operator" and the result should display "True" if a given word is found in string
mystery_string = "Hello, world!"
#You may modify the lines of code above, but don't move them!
#When you Submit your code, we'll change these lines to
#assign different values to the variables.
#The 'in' operator can be used to see if a string of characters
#is found within another string of characters, just like it can
#be used to find if an item is in a list.
#Above we've created a string with the variable name
#mystery_string. Write some code below that will print True
#if the string "world" appears within mystery_string, and
#False if it does not.
#Write your code here!
if "world" in mystery_string:
print("True")
else:
print("False")
#dropdown in the top left:
#We found the str "True" declared in your code. You shouldn't be creating this value
#manually.`
"world" in mystery_string returns a boolean value. You should not have to print True or false manually. Instead, you can do print("world" in mystery_string). This should print true if world is in string else print false.
print("world" in mystery_string)
Finally, it worked!

Python in function not finding string in tuple?

def bestInvitation(first, second):
yeah=tuple(zip(first, second))
res=list(set.intersection(*map(set, yeah)))
common=str(res)
count=0
for i in yeah:
if common in i:
count+=1
return count
if __name__ == '__main__':
print(bestInvitation(["fishing", "gardening", "swimming", "fishing"],
["hunting", "fishing", "fishing", "biting"]))
In the code above, line 6 should find the number of times that the common element between the 4 pairs of activities. This example should return 4 because fishing is a common element which occurs 4 times. However, it is returning 0. I think it's because common is not just a string, but a list of one string, but I don't know how to turn res into just a string. Any recommendations?
A simple print statement makes the problem clear:
...
for i in yeah:
print(common, i)
if common in i:
...
Output:
['fishing'] ('fishing', 'hunting')
['fishing'] ('gardening', 'fishing')
['fishing'] ('swimming', 'fishing')
['fishing'] ('fishing', 'biting')
You did not search for a string in a tuple of strings: you search for a string image of a list containing a string within your tuple. Since there is no such entity inside your tuple, the if statement fails on every iteration.
Fix your data handling -- one line:
common=str(res[0])
Now you get the desired output of 4.

Comparing string including decimal in Python

I have question here:
How do I compare variable that has string+decimal in Python.
Example :
a = "2.11.22-abc-def-ghi"
if a == (2.11*) :
print "ok"
I want it only compare the first 2 decimal point only and it doesn't care the rest of it value. How can I do that?
Thanks
Here's the most direct answer to your question, I think...a way to code what your pseudocode is getting at:
a = "2.11.22-abc-def-ghi"
if a.startswith("2.11"):
print("ok")
If you want to grab the numeric value off the front, turn it into a true number, and use that in a comparison, no matter what the specific value, you could do this:
import re
a = "2.11.22-abc-def-ghi"
m = re.match(r"(\d+\.\d+).*", a)
if m:
f = float(m.group(1))
if (f == 2.11):
print("ok")
If you want to compare part of a string, you can always slice it with the syntax str[start_index: end_index] and then compare the slice. Please note the start_index is inclusive and end_index is exclusive. For example
name = "Eric Johnson"
name[0:3] #value of the slice is "Eri" no "Eric".
in your case, you can do
if a[0:4] == "2.11":
#stuff next

How to check whether a value is in a list

I'm running in to a problem with my code. What needs to happen is:
Program asks what your movie channel name is,
Program asks what the code is that you received,
Program checks whether the code you received matches the movie channel you specified,
Program returns a print statement based on the result. If the code was found, print "Match", otherwise print "not found"
The code I have so far is:
def code_controle():
moviechannel = input("What is the name of your movie channel?")
code = input("What is the code you want to check?")
list = [
["RTL8", "20:30", "Rush", "John", "Smith", "123"],
["Veronica", "15:00", "V for Vendetta", "Jane", "Smith" , "ABC"]
]
Now what I need to do is match the moviechannel with a code.
Basically, if I put in "RTL8" and the code "123" it should look through all the lists starting with RTL8, then check the code I put in, with the code in the list. If this matches each other, print "match".
A simple solution is to iterate over the main list and check if the movie and code both exist in any sublist.
Python allows for checking values in a list using in. It is simply if 'value' in list
Writing a method as the one below could be useful if you want to call it often.
for sublist in list:
if movie in sublist and code in sublist:
return True
return False
Edit:
The above code will return true even if the movie and code values are interchanged. If the code is an unique identifier it should be fine, as no movie title would match it.
Since the list is generated by reading from an .csv file, and we are assured that the movie will always be the first item and the code the sixth, we can use the below code for exactly matching only those values.
for sublist in list:
if (movie == sublist[0]) and (code == sublist[5]):
return True
return False
I would wrap that in a try/except to catch any Index out of range just to be safe.
You could tackle that using python dictionaries, but to continue with your example:
found=0
for x in list: #note, change this, list is a type def
if x[0]==code and x[-1]==channel:
found+=1
print "Match"
if (found==0):
print "No match"
I'm assuming this is what you mean:
for line in list:
if moviechannel in line and code in line:
print('Match')
return
print('not found')
Btw you really should reconsider renaming your list, since that is also a built in function.
try this:
>>> my_list = set([moviechannel] + [code])
>>> for x in list:
... if len(set(x) & my_list) == 2:
... print "Match"
...
Match
This is an other way to do it:
new_list = c_list[0] + c_list[1]
if code in new_list and moviechannel in new_list:
print 'Match'
else:
print 'Not found'
You should not use list as list is a built-in function so I changed it to c_list.

Local variable 'list' referenced before assignment

I made a simple script that converts any input text into a "code" and can also translate it back. It only works one word at a time.
I want to make the script adds each new code to a list that is printed every time. For example, the first time you translate something, "HELLO" becomes "lohleci". The second time, I want it not only to show "world" = "ldwropx", but also state below everything translated so far.
I'm new to Python and have looked through forums for people with similar problems. The way I tried doing it (a segment was removed and put into a separate script), I get an error saying "local variable 'list' referenced before assignment." This is the code producing the error:
list = "none"
def list():
word = raw_input("")
if list == "none":
list = word + " "
print list
list()
else:
new_list = list + word + " "
list = new_list
print list
list()
list()
Your code has several problems, all of which are fixable with a bit more knowledge.
Don't use the name list for your own variables or functions. It's the name of a built-in Python function, and if you use that name for your own functions you won't be able to call the built-in function. (At least, not without resorting to advanced tricks which you shouldn't be trying to learn yet.)
You're also re-using the same name (list) for two different things, a variable and a function. Don't do that; give them different, meaningful names which reflect what they are. E.g., wordlist for the variable that contains a list of words, and get_words() for your function.
Instead of using a variable named list where you accumulate a set of strings, but which isn't actually a Python list, why not use a real Python list? They're designed for exactly what you want to do.
You use Python lists like this:
wordlist = []
# To add words at the end of the list:
wordlist.append("hello")
# To print the list in format ["word", "word 2", "word 3"]:
print wordlist
# To put a single space between each item of the list, then print it:
print " ".join(wordlist)
# To put a comma-and-space between each item of the list, then print it:
print ", ".join(wordlist)
Don't worry too much about the join() function, and why the separator (the string that goes between the list items) comes before the join(), just yet. That gets into classes, instances, and methods, which you'll learn later. For now, focus on using lists properly.
Also, if you use lists properly, you'll have no need for that if list == "none" check you're doing, because you can append() to an empty list just as well as to a list with contents. So your code would become:
Example A
wordlist = []
def translate_this(word):
# Define this however you like
return word
def get_words():
word = raw_input("")
translated_word = translate_this(word)
wordlist.append(translated_word)
print " ".join(wordlist)
# Or: print ", ".join(wordlist)
get_words()
get_words()
Now there's one more change I'd suggest making. Instead of calling your function at the end every time, use a while loop. The condition of the while loop can be anything you like; in particular, if you make the condition to be the Python value True, then the loop will never exit and keep on looping forever, like so:
Example B
wordlist = []
def translate_this(word):
# Define this however you like
return word
def get_words():
while True:
word = raw_input("")
translated_word = translate_this(word)
wordlist.append(translated_word)
print " ".join(wordlist)
# Or: print ", ".join(wordlist)
get_words()
Finally, if you want to get out of a loop (any loop, not just an infinite loop) early, you can use the break statement:
Example C
wordlist = []
def translate_this(word):
# Define this however you like
return word
def get_words():
while True:
word = raw_input("")
if word == "quit":
break
translated_word = translate_this(word)
wordlist.append(translated_word)
print " ".join(wordlist)
# Or: print ", ".join(wordlist)
get_words()
That should solve most of your problems so far. If you have any questions about how any of this code works, let me know.

Categories

Resources