i am new python and need to know how to print one of theis list by typing a or b or c, i tried useing if condtions and it's working but what if i have 100 of theis lists is there a better way thanks.
letters = input("Select a letter ")
a = ["aaaa","aaaa","aaaa","aaaa",]
b = ["bbbb","bbbb","bbbb","bbbb",]
c = ["CCCC","CCCC","CCCC","CCCC",]
if letters == "a":
print(a)
elif letters == "b":
print(b)
elif letters == "c":
print(c)
else:
print("wrong input")
The easiest way is to call eval.
print(eval("a"))
print(eval(letters)) # beware
However, one must never directly evaluate any raw input obtained from a user since they can then enter a command that would make the program do something arbitrary, like bypass restrictions, steal data or wipe your files. User input must always be processed or vetted fully:
if letters in ["a", "b", "c"]:
print(eval(letters)) # safe
else:
print("wrong input")
Another way to do it is to use the built-in function locals(). It returns a dictionary of all variables and values accessible within the local scope.
if letters in ["a", "b", "c"]:
print(locals()[letters])
Related
I am new to python and my coding experience so far is with MATLAB.
I am trying to understand more about lists and dictionaries as i am using a library about DOEs that takes an dictionary as a passing argument.
But my trouble so far is that this dictionary assumes the form of ex.
DOE={'Elastic Modulus':[10,20,30], 'Density':[1,2,3], 'Thickness':[2,3,5]}
But i need this dictionary to be user defined, for example:
Have an input to define how many variables are needed (in this example are 3: Elastic Modulus','Density'and 'Thickness)
as the variables are defined, it should be able to store values in the dictionary over a for loop.
Is this possible using dictionaries?
Or is it better to use a list and convert in a dicionary later?
Thank you in advance
One can add keys and the corresponding values to a dict one at a time like so:
my_dict = {}
num_entries = int(input("How many entries "))
for _ in range(num_entries):
key = input("Enter the key: ")
value = input("Enter the value: ")
my_dict[key] = value
Presumably you would have a loop to do the entry of key and value for the number of values you wish to enter. Also if you are in python 2 it needs to be raw_input rather than input function. [Edit: Showing how to do the loop, since I noticed that was part of your question]
I'm having trouble converting my working code from lists to dictionaries. The basics of the code checks a file name for any keywords within the list.
But I'm having a tough time understanding dictionaries to convert it. I am trying to pull the name of each key and compare it to the file name like I did with lists and tuples. Here is a mock version of what i was doing.
fname = "../crazyfdsfd/fds/ss/rabbit.txt"
hollow = "SFV"
blank = "2008"
empty = "bender"
# things is list
things = ["sheep", "goat", "rabbit"]
# other is tuple
other = ("sheep", "goat", "rabbit")
#stuff is dictionary
stuff = {"sheep": 2, "goat": 5, "rabbit": 6}
try:
print(type(things), "things")
for i in things:
if i in fname:
hollow = str(i)
print(hollow)
if hollow == things[2]:
print("PERFECT")
except:
print("c-c-c-combo breaker")
print("\n \n")
try:
print(type(other), "other")
for i in other:
if i in fname:
blank = str(i)
print(blank)
if blank == other[2]:
print("Yes. You. Can.")
except:
print("THANKS OBAMA")
print("\n \n")
try:
print(type(stuff), "stuff")
for i in stuff: # problem loop
if i in fname:
empty = str(i)
print(empty)
if empty == stuff[2]: # problem line
print("Shut up and take my money!")
except:
print("CURSE YOU ZOIDBERG!")
I am able to get a full run though the first two examples, but I cannot get the dictionary to run without its exception. The loop is not converting empty into stuff[2]'s value. Leaving money regrettably in fry's pocket. Let me know if my example isn't clear enough for what I am asking. The dictionary is just short cutting counting lists and adding files to other variables.
A dictionary is an unordered collection that maps keys to values. If you define stuff to be:
stuff = {"sheep": 2, "goat": 5, "rabbit": 6}
You can refer to its elements with:
stuff['sheep'], stuff['goat'], stuff['rabbit']
stuff[2] will result in a KeyError, because the key 2 is not found in your dictionary. You can't compare a string with the last or 3rd value of a dictionary, because the dictionary is not stored in an ordered sequence (the internal ordering is based on hashing). Use a list or tuple for an ordered sequence - if you need to compare to the last item.
If you want to traverse a dictionary, you can use this as a template:
for k, v in stuff.items():
if k == 'rabbit':
# do something - k will be 'rabbit' and v will be 6
If you want to check to check the keys in a dictionary to see if they match part of a string:
for k in stuff.keys():
if k in fname:
print('found', k)
Some other notes:
The KeyError would be much easier to notice... if you took out your try/except blocks. Hiding python errors from end-users can be useful. Hiding that information from YOU is a bad idea - especially when you're debugging an initial pass at code.
You can compare to the last item in a list or tuple with:
if hollow == things[-1]:
if that is what you're trying to do.
In your last loop: empty == str(i) needs to be empty = str(i).
Some background
I'm asking how a programmer would approach this task because I'm not really a programmer. I'm a grad student studying quantitative social science, and while I've been programming consistently for a year now I have no formal training.
I'm not concerned about implementing a generic algorithm. I'm happy to work in Bash, AWK, R, or Python. I've also written small snippets of code (beyond "hello world," but not much further) in Java, C, JavaScript, and Matlab. However, if there's some language or some feature of a language that would make this task easier or more natural, I'd love to know about it.
Instead, I'm interested in algorithms and data structures. What do I grab, when do I grab it, where do I save it, etc.? I imagine I could probably do all this with a few cleverly-constructed regular expressions, and I am pretty comfortable with intermediate-level regex features like lookarounds, but anything I make up on my own will undoubtedly be hacky and ad-hoc.
The task
What I have is code (it happens to be in R) that looks something like this, where #'s indicate comments:
items = list(
day1 = list(
# a apples
# b oranges
# c pears
# d red grapes
# m.
# 1 peanuts
# 2 cashews
type1 = c("a", "b", "d", "m.2") # this returns a vector of strings
type2 = c("c", "m.1")
), # this returns a list of vectors
day2 = list(
# a apples
# b oranges
# c pears
# d red grapes
# e plums
# m.
# 1 peanuts
# 2 cashews
# 3 pistachios
type1 = c("a", "b", "d", "e", "m.2")
type2 = c("c", "m.1", "m.3")
)
) # this returns a list of lists of vectors
and what I would like instead is code that looks like this:
items = list(
day1 = list(
type1 = c(
"apples" = "a",
"oranges" = "b",
"red grapes" = "d",
"cashews" = "m.2"
),
type2 = c(
"pears" = "c",
"peanuts" = "m.1"
)
),
day2 = list(
type1 = c(
"apples" = "a",
"oranges" = "b",
"red grapes" = "d",
"plums" = "e",
"cashews" = "m.2"
),
type2 = c(
"pears" = "c",
"peanuts" = "m.1",
"pistachios" = "m.3"
)
)
)
Some things to note:
I can rely on the commented text following that format.
I cannot rely on the naming for day1 being "nested" inside the naming for day2. Some of the letters might swap around.
I can rely on there being the same number and name of types within days.
The vertical spacing isn't important; I mostly just want to get the comments into the code as shown, although having the script do all the spacing for me would be a nice touch.
So, how would a programmer approach the task of programmatically turning the first code snippet into the second? I can have it done in about 15 minutes of copying and pasting, but I'd like to learn something here. And again, I'm not asking for pre-written code, I'm just looking for some direction since right now I'm just groping in the dark.
Given your sample of code it should be doable by putting together a transformation that consists of a couple steps. At a high level you'd need to read the comments into a data collection that you can query, then parse the code and do a find/replace referencing the data collection.
Without getting in too deep this might look like:
Generate a text file of only the comments. Using a regex with the intent of "find all lines that start with whitespace, then a #" (something like ^\s*#.*$) would give you a result like:
# a apples
# b oranges
# c pears
# d red grapes
# m.
# 1 peanuts
# 2 cashews
# a apples
# b oranges
# c pears
# d red grapes
# e plums
# m.
# 1 peanuts
# 2 cashews
# 3 pistachios
Using the above results you can utilize some basic text parsing to break down each line. To handle the m. cases requires some assumptions. Based on your sample I'd start with some pseudocode like:
For each line
Get the first character after the # and call it "key"
Find the word after the letter and call it "value"
If the key is a letter
Add "key" => "value" to the dictionary
Next line
If the key is a number
Get the last key added to the dictionary and call it as "parentkey"
Add "parentkey"+"key" => "value" to the dictionary
Next line
This would give you a structure like this:
{
"a": "apples",
"b": "oranges",
"c": "pears",
"d": "red grapes",
"m.": "",
"m.1": "peanuts",
"m.2": "cashews",
"a": "apples",
"b": "oranges",
"c": "pears",
"d": "red grapes",
"e": "plums",
"m.": "",
"m.1": "peanuts",
"m.2": "cashews",
"m.3": "pistachios"
}
You can clean out the empty "m." entries by iterating over it and removing items with an empty value.
At this point you can iterate over your dictionary and perform an find/replace in your code file:
For each dictionary entry (key, value)
Find strings like "key" and replace with strings like "value" = "key"
All in all it's not terribly efficient or elegant, but it's not difficult to code and should work. Granted there's probably additional details to consider (there always are) but this is a fairly simple approach given your samples.
I would use a quick regular expression substitution to reduce the work to do and then fix it up by hand. For example you get over halfway there with:
s/# (\w+) ([\w ]+)/"\2" = "\1"/
The exact regular expression to write and how you use it depends on your tool. Different editors and programming languages are very different. Google for what you are using to learn more. (You may have multiple easy options - a Python command line would use one syntax, and the vi editor a different one.)
If you have to do this task regularly or for more code, then you would need to learn about parsing. Which is a lot more work (too much to be worthwhile for something like this if you don't have code sitting around to do it) but also a lot more powerful in the long run.
I'm a new programmer and I'm having a difficult time finishing up my 4th program. The premise was to create a program that would take input from the user, creating a list then compares this list to a tuple. After it prints a statement letting the user know which items they chose correspond to the items in the tuple and also in which position they are in the tuple.
The problem I'm having is the last part, I can't get the correct position to print right and I fail to understand why. For example, if someone chose GPS correctly during their guesses, it should print position 0, but it doesn't. If water is chosen, it says it's in position 13...but it should be 5.
#here is the code I have so far:
number_items_input = 0
guessed_inventory_list = [] #this is the variable list that will be input by user
survival_gear = () #this is the tuple that will be compared against
survival_gear = ("GPS","map","compass","firstaid","water","flashlight","lighter","blanket","rope","cell phone","signal mirror")
#block bellow takes input from the user
print("Please choose one by one, which top 10 items do you want with you in case of a survival situation, think Bear Grylls. Once chosen, your list will be compared to the top 10 survival items list.")
while number_items_input < 10:
print("Please choose.")
guessed_items = input()
guessed_inventory_list.append(guessed_items)
number_items_input = number_items_input + 1
print ("You have chosen the following:", guessed_inventory_list)
#block of code below here compares the input to the tuple
t = 1
while t < 1:
t = t + 1
for individual_items in guessed_inventory_list:
for top_items in survival_gear:
if individual_items == top_items:
#finally the print statements below advise the user if they guessed an item and which position it's in.
print ("You have chosen wisely", top_items)
print ("It's in position", t, "on the survival list")
t = t + 1
The reason you are getting a wrong index is because of the wrong nesting of loops , your outer loop should be the tuple you wish to compare and the inner loop should be the list generated from the input where as in this case it is reverse, see the below corrected code snippet
Code snippet:
for top_items in survival_gear:
for individual_items in guessed_inventory_list:
if individual_items == top_items:
#finally the print statements below advise the user if they guessed an item and which position it's in.
print ("You have chosen wisely", top_items)
print ("It's in position", t, "on the survival list")
t = t + 1
The above code snippet should solve your problem , but your code contains
while loop which can be avoided using the range built in function
Incrementing the variable t manually can be avoided by using enumerate built in function
The nested forloop and if loop can be replaced by using the "in" membership test operator
Find the below updated code:
#!/usr/bin/python
number_items_input = 0
guessed_inventory_list = [] #this is the variable list that will be input by user
survival_gear = ("GPS","map","compass","firstaid","water","flashlight","lighter","blanket","rope","cell phone","signal mirror")
#block bellow takes input from the user
print("Please choose one by one, which top 10 items do you want with you in caseof a survival situation, think Bear Grylls.Once chosen, your list will be compared to the top 10 survival items list.")
# One can use range functions to loop n times in this case 10 times
for i in range(0,10):
guessed_items = raw_input("Please choose:")
guessed_inventory_list.append(guessed_items)
print ("You have chosen the following:", guessed_inventory_list)
# Enumerate is one of the built-in Python functions.
# It returns an enumerate object.
# In this case that object is a list of tuples (immutable lists),
# each containing a pair of count/index and value.
# like [(1, 'GPS'), (2, 'map'), (3, 'compass'),...,(6, 'signal mirror')]
# in the below for loop the list of tuple will be
#unpacked in to t and individual_items for each iteration
for t,individual_items in enumerate(survival_gear,start=1):
#the "in" is a membership test operator which will test whether
#individual_items is in list guessed_inventory_list
if individual_items in guessed_inventory_list:
#finally the print statements below advise the user if they guessed an item and which position it's in.
print("You have chosen wisely", individual_items)
print("It's in position", t, "on the survival list")
I am using the following regexp to match all occurrences of a special kind of number:
^([0-57-9]|E)[12][0-9]{3}[A-Z]?[A-Z]([0-9]{3}|[0-9]{4})
Let's assume that this regex matches the following five numbers:
31971R0974
11957E075
31971R0974-A01P2
31971R0974-A05
51992PC0405
These matches are then printed using the following code. This prints each item in the list and if the item contains a dash, everything after the dash is discarded.
def number_function():
for x in range(0, 10):
print("Number", number_variable[x].split('-', 1)[0])
However, this would print five lines where lines 1, 3 and 4 would be the same.
I need your help to write a script which compares each item with all previous items and only prints the item if it does not already exist.
So, the desired output would be the following three lines:
31971R0974
11957E075
51992PC0405
EDIT 2:
I solved it! I just needed to do some moving around. Here's the finished product:
def instrument_function():
desired = set()
for x in range(0, 50):
try:
instruments_celex[x]
except IndexError:
pass
else:
before_dash = instruments_celex[x].split('-', 1)[0]
desired.add(before_dash)
for x in desired:
print("Cited instrument", x)
I've done practically no python up until now, but this might do what you're after
def number_function():
desired = set()
for x in range(0, 10):
before_hyphen = number_variable[x].split('-', 1)[0]
desired.add(before_hyphen)
for x in desired:
print("Number", x)
Here is a version of your "finished" function that is more reaonable.
# Don't use instruments_celex as a global variable, that's terrible.
# Pass it in to the function instead:
def instrument_function(instruments_celex):
unique = set()
# In Python you don't need an integer loop variable. This is not Java.
# Just loop over the list:
for entry in instruments_celex:
unique.add(entry.split('-', 1)[0])
for entry in unique:
print("Cited instrument", entry)
You can also make use of generator expressions to make this shorter:
def instrument_function(instruments_celex):
unique = set(entry.split('-', 1)[0] for entry in instruments_celex)
for entry in set:
print("Cited instrument", entry)
That's it. It's so simple in fact that I wouldn't make a separate function of it unless I do it at least two times in the program.