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.
Related
I'm working on a python/beautifulsoup web scraper. I'm searching for certain keywords, my statement looks like this:
if 'tribe' in entry or 'ai1ec' in entry or 'tfly' in entry:
print('Plugin Found!')
rating = easy
sheet.cell(row=i, column=12).value = rating
What I would like to do is find out which one of those keywords is making the statement true. My first instinct would be to write a nested loop to check but I wasn't sure if there was a way to capture the value that makes the statement true that would involve less code?
I would use a generator comprehension that I would pass to next with a default value. If the comprehension doesn't find anything, next returns the default value, else it returns the first found and stops there (kind of any, but which stores the result)
cases = ['tribe','allec','tfly']
entry = 'iiii allec rrrr'
p = next((x for x in cases if x in entry),None)
if p is not None:
print('Plugin Found!',p)
[EDIT: changed to only find first name]
for name in ('tribe', 'ailec', 'tfly'):
if name in entry:
print ('Name =', name)
print('Plugin Found!')
rating = easy
sheet.cell(row=i, column=12).value = rating
break
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.
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.
I want to sort a string that contains email addresses to a list of email addresses.
The code gets stuck and nothing happens.
unsorted = "sge#grg.lt ggrge#yahoo.com"
def sort_thatstring():
s = ""
out = []
for x in unsorted:
s = ""
while x != " ":
s+=str(x)
else:
out.append(s)
sort_thatstring()
print out
I would like to get:
out = ["sge#grg.lt", "ggrge#yahoo.com"]
You can do:
sorted_list = sorted(unsorted.split(), key=lambda x: x.split('#')[1])
print(sorted_list)
#['sge#grg.lt', 'ggrge#yahoo.com']
Your code has two issues:
You reset s every time you loop in the for loop causing you to loose the data you have read.
The while statement also constructs a loop, but you are using it like an if. Try replacing while with if and read up on the difference between conditionals and loop constructors.
Your function also needs to return the out array otherwise it will be destroyed as soon as your function reaches the end.
I am trying to compare values from 2 Dictionaries in Python. I want to know if a value from one Dictionary exists anywhere in another Dictionary. Here is what i have so far. If it exists I want to return True, else False.
The code I have is close, but not working right.
I'm using VS2012 with Python Plugin
I'm passing both Dictionary items into the functions.
def NameExists(best_guess, line):
return all (line in best_guess.values() #Getting Generator Exit Error here on values
for value in line['full name'])
Also, I want to see if there are duplicates within best_guess itself.
def CheckDuplicates(best_guess, line):
if len(set(best_guess.values())) != len(best_guess):
return True
else:
return False
As error is about generator exit, I guess you use python 3.x. So best_guess.values() is a generator, which exhaust for the first value in line['full name'] for which a match will not be found.
Also, I guess all usage is incorrect, if you look for any value to exist (not sure, from which one dictinary though).
You can use something like follows, providing line is the second dictionary:
def NameExists(best_guess, line):
vals = set(best_guess.values())
return bool(set(line.values()).intersection(vals))
The syntax in NameExists seems wrong, you aren't using the value and best_guess.values() is returning an iterator, so in will only work once, unless we convert it to a list or a set (you are using Python 3.x, aren't you?). I believe this is what you meant:
def NameExists(best_guess, line):
vals = set(best_guess.values())
return all(value in vals for value in line['full name'])
And the CheckDuplicates function can be written in a shorter way like this:
def CheckDuplicates(best_guess, line):
return len(set(best_guess.values())) != len(best_guess)