How can I create a loop that prompts for a list of items, with the prompt changing each time.
For example "Input your first item" then "Input your second item" etc... (or 1st, 2nd)
I need to add all of the items to an array:
items = []
for i in range(5):
item = input("Input your first thing: ")
items.append(item)
print (items)
Use a list of prompts:
prompts = ('first', 'second', 'third', 'fourth', 'fifth')
items = []
for prompt in prompts:
item = input("Input your {} thing: ".format(prompt))
items.append(item)
Slightly altering your code:
names = {1: "first", 2: "second", 3: "third" # and so on...
}
items = []
for i in range(5):
item = input("Input your {} thing: ".format(names[i+1])
items.append(item)
print(items)
Or a more general version:
def getordinal(n):
if str(n)[-2:] in ("11","12","13"):
return "{}th".format(n)
elif str(n)[-1] == "1":
return "{}st".format(n)
elif str(n)[-1] == "2":
return "{}nd".format(n)
elif str(n)[-1] == "3":
return "{}rd".format(n)
else:
return "{}th".format(n)
Or a more compact definition:
def getord(n):
s=str(n)
return s+("th" if s[-2:] in ("11","12","13") else ((["st","nd","rd"]+
["th" for i in range(7)])
[int(s[-1])-1]))
Why not use string formatting? Something along the lines of
>>> for i in range(5):
items.append(input("Enter item at position {}: ".format(i)))
from collections import OrderedDict
items = OrderedDict.fromkeys(['first', 'second', 'third', 'fourth', 'fifth'])
for item in items:
items[item] = raw_input("Input your {} item: ".format(item))
print items
Output:
Input your first item: foo
Input your second item: bar
Input your third item: baz
Input your fourth item: python
Input your fifth item: rocks
OrderedDict([('first', 'foo'), ('second', 'bar'), ('third', 'baz'), ('fourth', 'python'), ('fifth', 'rocks')])
Related
How to compare the value in a string list with another value in a string list and if I do succeed in comparing with 2 of the lists, how can I store a new value in a new list if the value in the string lists is matches?
def start_game():
food_list = ["salad", "steak", "fries", "rice", "noodles", "fruits"]
random_food_list = [random.choices (food_list, k = 4)]
player_guess_list = []
correct_guess_list = []
for i in range(1,5):
player_guess = input("food" + str(i) + ":").lower()
if player_guess not in food_list:
print("Invalid foods, Restart Again")
start_game()
else:
player_guess_list.append(player_guess)
print(player_guess_list) # For review
print(random_food_list) # For review
For example:
User input list = [salad, steak, noodles, rice]
randomized list = [salad, rice, salad, rice]
correct_guess_list = [O,X,X,O]
Output
Correct food in correct place: 2
Correct food in wrong place: 2
You can do what you by using a single list comprehension of the values in the two list zipped together.
food_list = ["salad", "steak", "fries", "rice", "noodles", "fruits"]
#random_food_list = random.choices(food_list, k = 4)
random_food_list = ['salad', 'rice', 'salad', 'rice'] # Hardcode for testing.
correct_guess_list = ['O' if f1.lower() == f2.lower() else 'X'
for f1, f2 in zip(food_list, random_food_list)]
print(correct_guess_list) # -> ['O', 'X', 'X', 'O']
correct_food_in_correct_place = correct_guess_list.count('O')
correct_food_in_wrong_place = correct_guess_list.count('X')
print(f'Correct food in correct place: {correct_food_in_correct_place}') # -> 2
print(f'Correct food in wrong place: {correct_food_in_wrong_place}') # -> 2
The question is quite unclear. The example looks like you want to compare two lists and create a third list that stores where the first two lists are identical.
This can be done this way:
user_input_list = ["salad", "steak", "noodles", "rice"]
randomized_list = ["salad", "rice", "salad", "rice"]
new_list = list(map(lambda x, y : 'O' if x == y else 'X', \
user_input_list, \
randomized_list))
correct_food_in_correct_place = new_list.count('O')
correct_food_in_wrong_place = new_list.count('X')
print(new_list)
print(correct_food_in_correct_place)
print(correct_food_in_wrong_place)
Sorry, that is already quite heavy Python code. Not really easy for beginners. Try it out and you will see what it does. If this does not answer your question, please ask ask more concretely and try to isolate your problem a bit.
I made the correct guesses list using a list comprehension:
correct_guess_list = ["O " if random_food_list[player_guess_list.index(food)] == food else "X" for food in
player_guess_list]
Full code:
import random
def start_game():
food_list = ["salad", "steak", "fries", "rice", "noodles", "fruits"]
random_food_list = random.choices(food_list, k=4)
player_guess_list = []
correct_guess_list = []
correct_guesses = 0
for i in range(1, 5):
player_guess = input("food" + str(i) + ":").lower()
if player_guess not in food_list:
print("Invalid foods, Restart Again")
start_game()
else:
player_guess_list.append(player_guess)
if player_guess_list[i-1] == random_food_list[i-1]:
correct_guesses += 1
print(player_guess_list) # For review
print(random_food_list) # For review
correct_guess_list = ["O " if random_food_list[player_guess_list.index(food)] == food else "X" for food in
player_guess_list]
print(correct_guess_list)
print(f"Food in correct place: {correct_guesses}")
print(f"Food in incorrect place: {4 - correct_guesses}")
start_game()
One problem I see in your anser is you are creating a list of list rather than list to compare with in the first place random.choices (food_list, k = 4) returns a list so no need to enclose it in square brackets. Now both the types will be list and you can use indexing to compare values from both list.
import random
def start_game():
food_list = ["salad", "steak", "fries", "rice", "noodles", "fruits"]
random_food_list = random.choices (food_list, k = 4)
player_guess_list = []
correct_guess_list = []
for i in range(1,5):
player_guess = input("food" + str(i) + ":").lower()
if player_guess not in food_list:
print("Invadlid foods, Restart Again")
start_game()
else:
player_guess_list.append(player_guess)
print(player_guess_list) # For review
print(random_food_list) # For review
for i in range(0 , len(random_food_list)):
if random_food_list[i] == player_guess_list[i]:
correct_guess_list.append(random_food_list[i])
print(correct_guess_list)
start_game()
I've been searching for a solution for hours, but I can't find anything that helps. I'm having a problem converting a list of tuples into a dictionary. I get this error: 'ValueError: dictionary update sequence element #320 has length 1; 2 is required.' Here is a small example of the list of tuples:
[('Heat_equation', 262), ('Portal:Tertiary_Educatio', 262), ('Help:Wiki_markup_example', 262), ('Quantum_mechanics', 262), ('IB_Language_A:_English_Language_and_Literature_Course_Materia', 261), ('Pulmonary_Plethor', 261)]
This is what I want:
{'Heat_equation': 262, 'Portal:Tertiary_Educatio': 262, 'Help:Wiki_markup_example': 262, 'Quantum_mechanics': 262, 'IB_Language_A:_English_Language_and_Literature_Course_Materia': 261, 'Pulmonary_Plethor': 261}
The length is 2 though right? I'm not sure why I'm getting an error. Here is the function where I'm trying to convert the list of tuples into a dictionary:
import urllib.request
import json
import re
def get_url(url):
text = urllib.request.urlopen(url).read().decode()
return text
def get_choice():
try:
print("Select from the following options or press <?> to quit:")
print("1. Display top 1000 articles and views.")
print("2. Display top 100 learning projects.")
choice = input()
choice = int(choice)
if 1 <= choice <= 2:
print()
return choice
except ValueError:
if choice == "":
return None
print("%s is not a valid choice.\n" % choice)
def display_json(text):
lst = []
dictionary = json.loads(text)
for item in dictionary['items']:
for article in item['articles']:
line = (article['article'], article['views'])
lst.append(line)
return lst
def convert_dict(lst):
d = dict()
[d[t[0]].append(t[1]) if t[0] in (d.keys())
else d.update({t[0]: [t[1]]}) for t in lst]
dictionary = {k: v[0] for k, v in d.items()}
return dictionary
def display_dict(dictionary):
print(dictionary)
def learning_project(dictionary):
lst_2 = []
for key, value in dictionary.items():
string = str(key)
match = re.findall(r'([^\/ ]+).*?\w+.*', string)
match.append(value)
tup = tuple(match)
lst_2.append(tup)
return lst_2
def convert(lst_2):
p = dict(lst_2)
print(p)
def main():
while True:
url = "https://wikimedia.org/api/rest_v1/metrics/pageviews/top/en.wikiversity/all-access/2018/01/all-days"
choice = get_choice()
if choice == None:
break
elif choice == 1:
text = get_url(url)
lst = display_json(text)
dictionary = convert_dict(lst)
display_dict(dictionary)
elif choice == 2:
text = get_url(url)
lst = display_json(text)
dictionary = convert_dict(lst)
lst_2 = learning_project(dictionary)
convert(lst_2)
main()
To explain the learning project function, I had a bigger dictionary I needed to parse. So I turned the key into a string and parsed the key with RegEx. I then appended the value to the key and that created rows of lists. Then I turned the rows of lists into tuples, and created a list of tuples. Now I'm just trying to turn this back into a dictionary, but it is not working. Any help is greatly appreciated!
if you are getting errors with p = dict(lst_2) then your input data is not compliant with your requirement. You could make the conversion more robust by ensuring that list elements are always a two entry tuple.
p = dict( (*t,None,None)[:2] for t in lst_2 or [])
This will not fix the data but it may allow you to move forward and perhaps detect the faulty data by finding None key or None values in the resulting dictionary.
data = [('Heat_equation', 262), ('Portal:Tertiary_Educatio', 262),
('Help:Wiki_markup_example', 262), ('Quantum_mechanics', 262),
('IB_Language_A:_English_Language_and_Literature_Course_Materia', 261),
('Pulmonary_Plethor', 261)]
mydict = dict(data)
I am trying to print the results from all 3 names that are input, in a dictionary format. Current code below only prints out the last name. The 2 lines commented out (#) are what I was trying to change around to get it to work, clearly not doing it correctly.
def name():
count = 0
while (count < 5):
d = {}
qs = dict(Fname='first name', Lname='last name')
for k,v in qs.items():
d[k] = input('Please enter your {}: '.format(v))
#d['first name'].append(v)
#d['last name'].append(v)
count += 1
print(d)
name()
A few things that I'd change:
append each record (dictionary) to a list of entries.
(optional) Use a for-loop rather than a while as less lines of code.
return the entries list, rather than print it as it is a function so I like to have outputs.
So here's the corrected code:
def name():
entries = []
for count in range(5):
d = {}
qs = dict(Fname='first name', Lname='last name')
for k, v in qs.items():
d[k] = input('Please enter your {}: '.format(v))
entries.append(d)
return entries
print(name())
For testing purpose, I modified it to just except 2 entries, but we can still see that it works:
Please enter your last name: fish
Please enter your first name: bowl
Please enter your last name: cat
Please enter your first name: mat
[{'Lname': 'fish', 'Fname': 'bowl'}, {'Lname': 'cat', 'Fname': 'mat'}]
Hope! you got it right from Martijin Comments, For reference to other adding this code:
def name():
count = 0
listOfDict = [] #creating empty list
for count in range(3):
dict = {}
qs = dict(Fname = 'first name', Lname = 'last name' )
for k,v in qs.items():
d[k] = input('please enter your {}: '.format(v))
listOfDict.append(d) # adding each item to the list.
count += 1
print listOfDict
name()
This should work:
def name():
count = 0
while (count < 5):
d = {}
qs = dict(Fname='first name', Lname='last name')
for k,v in qs.items():
a = input('Please enter your {}: '.format(v))
d[v] = a
count += 1
print(d['first name'],d['last name'])
name()
You can use defaultdict to automatically create lists to store each entered value. The main idea is that you want to append each entered value to a collection of some type (e.g. list).
from collections import defaultdict
number_of_entries = 3
dd = defaultdict(list)
for _ in range(number_of_entries):
for key in ('first name', 'last_name'):
dd[key].append(input('please enter you {}: '.format(key)))
>>> print(dict(dd))
{'first name': ['Adam', 'Milton', 'Irving'],
'last_name': ['Smith', 'Friedman', 'Fisher']}
I am reading data from file, like listed below, it is a .dat file:
1
Carmella Henderson
24.52
13.5
21.76
2
Christal Piper
14.98
11.01
21.75
3
Erma Park
12.11
13.51
18.18
4
Dorita Griffin
20.05
10.39
21.35
The file itself contains 50 records. From this data I need the person number, name and the first number, like so:
1 #person number
Marlon Holmes #Name
18.86 # First number
13.02 # Second Number
13.36 # Third Number
I already have code to read the data however I unable to get the top 10 results based on the #First number
The #First number in the Top 10 currently is in centimeters but needs to be converted to inches, I am unsure on how to combine the top 10 and conversion into one alongside the reading of the data
Code that reads the data:
with open('veggies_2016.txt', 'r') as f:
count = 0
excess_count = 0
for line in f:
if count < 3:
print(line)
count += 1
elif count == 3 and excess_count < 1:
excess_count += 1
else:
count = 0
excess_count = 0
As mentioned the code reads the file, like so #Person number, #name and #first number, but #first number needs to be converted to inches and then all of the data needs to be sorted to find the top 10
This process will also have to be repeated for #second number and #third number however they are separate in terms of their code from #first number
I have tried to read the data then append to a list and sort it and convert it from that but with no success, any help would be appreciated
Whole code:
from collections import OrderedDict
from operator import itemgetter
import pprint
def menu():
exit = False
while not exit:
print("To enter new competitior data, type new")
print("To view the competition score boards, type Scoreboard")
print("To view the Best Overall Growers Scoreboard, type Podium")
print("To review this years and previous data, type Data review")
print("Type quit to exit the program")
choice = raw_input("Which option would you like?")
if choice == 'new':
new_competitor()
elif choice == 'Scoreboard':
scoreboard_menu()
elif choice == 'Podium':
podium_place()
elif choice == 'Data review':
data_review()
elif choice == 'quit':
print("Goodbye")
raise SystemExit
"""Entering new competitor data: record competitor's name and vegtables lengths"""
def competitor_data():
global competitor_num
l = []
print("How many competitors would you like to enter?")
competitors = raw_input("Number of competitors:")
num_competitors = int(competitors)
for i in range(num_competitors):
name = raw_input("Enter competitor name:")
Cucumber = raw_input("Enter length of Cucumber:")
Carrot = raw_input("Enter length of Carrot:")
Runner_Beans = raw_input("Enter length of Runner Beans:")
l.append(competitor_num)
l.append(name)
l.append(Cucumber)
l.append(Carrot)
l.append(Runner_Beans)
competitor_num += 1
return (l)
def new_competitor():
with open('veggies_2016.txt', 'a') as f:
for item in competitor_data():
f.write("%s\n" %(item))
def scoreboard_menu():
exit = False
print("Which vegetable would you like the scoreboard for?")
vegetable = raw_input("Please type either Cucumber, Carrot or Runner Beans:")
if vegetable == "Cucumber":
Cucumber_Scoreboard()
elif vegetable == "Carrot":
Carrot_Scoreboard()
elif vegetable == "Runner Beans":
Runner_Beans_Scoreboard()
def Cucumber_Scoreboard():
exit = True
print("Which year would you like the Scoreboard from?")
scoreboard = raw_input("Please type a year:")
if scoreboard == "2015":
cucumber_veg_2015()
elif scoreboard == "2014":
cucumber_veg_2014()
elif scoreboard == "2016":
cucumber_veg_2016()
def cucumber_veg_2016(cm):
return float(cm) / 2.54
names = OrderedDict([('Competitor Number', int),
('Competitor Name', str),
('Cucumber', cucumber_veg_2016),
('Carrot', float),
('Runner Bean', float)])
data = []
with open('veggies_2016.txt') as fobj:
while True:
item = {}
try:
for name, func in names.items():
item[name] = func(next(fobj).strip())
data.append(item)
except StopIteration:
break
pprint.pprint(sorted(data, key=itemgetter('Cucumber'))[:10])
Solution
Reading the data into a list of dictionaries would work:
from collections import OrderedDict
from operator import itemgetter
import pprint
def to_inch(cm):
return float(cm) / 2.54
names = OrderedDict([('person_number', int),
('name', str),
('first', to_inch),
('second', float),
('third', float)])
data = []
with open('veggies_2016.txt') as fobj:
while True:
item = {}
try:
for name, func in names.items():
item[name] = func(next(fobj).strip())
data.append(item)
except StopIteration:
break
pprint.pprint(sorted(data, key=itemgetter('first'))[:10])
Output:
[{'first': 4.76771653543307,
'name': 'Erma Park',
'person_number': 3,
'second': 13.51,
'third': 18.18},
{'first': 5.897637795275591,
'name': 'Christal Piper',
'person_number': 2,
'second': 11.01,
'third': 21.75},
{'first': 7.893700787401575,
'name': 'Dorita Griffin',
'person_number': 4,
'second': 10.39,
'third': 21.35},
{'first': 9.653543307086613,
'name': 'Carmella Henderson',
'person_number': 1,
'second': 13.5,
'third': 21.76}]
In Steps
This helper function converts centimeters into inches:
def to_inch(cm):
return float(cm) / 2.54
We use an ordered dictionary to hold the names for the different items we want to read in order. The value is a function that we use to convert the read value for each item:
names = OrderedDict([('person_number', int),
('name', str),
('first', to_inch),
('second', float),
('third', float)])
We start with an empty list:
data = []
And open our file:
with open('veggies_2016.txt') as fobj:
We do something without a defined end and create a new dictionary item each time:
while True:
item = {}
We try to read from the file until it is finished, i.e. until we get a
StopIteration exception:
try:
for name, func in names.items():
item[name] = func(next(fobj).strip())
data.append(item)
except StopIteration:
break
We go through the keys and values of our order dictionary names and call each
value, i.e. the function func() on the next line we retrieve with next().
This converts the entry into the desired datatype and does the cm-inch conversion for first. After reading all items for one person, we append the dictionary to the list data.
Finally, we sort by the key first and print out the 10 to entries
(my example file has less than 10 entries):
pprint.pprint(sorted(data, key=itemgetter('first'))[:10])
Integration with your code:
You need to put the code into the function podium_place():
def cucumber_veg_2016(cm):
return float(cm) / 2.54
def podium_place():
names = OrderedDict([('Competitor Number', int),
('Competitor Name', str),
('Cucumber', cucumber_veg_2016),
('Carrot', float),
('Runner Bean', float)])
data = []
with open('veggies_2016.txt') as fobj:
while True:
item = OrderedDict()
try:
for name, func in names.items():
item[name] = func(next(fobj).strip())
data.append(item)
except StopIteration:
break
sorted_data = sorted(data, key=itemgetter('Cucumber'), reverse=True)
for entry in sorted_data[:10]:
for key, value in entry.items():
print key, value
print
menu()
At the end you need to call menu(). Also, if top mean largest first, you need sort reverse (see above).
I would read them as a record at a time. You can put that functionality in a function that you call several times with the same file. It can return a None when you reach the end of the file. It will return a tuple with all values for a given record (including conversions). You can then use sorted to sort the list of records using any one of the values from each record.
def read_record(fid):
id = fid.readline()
# At the end of the file
if id is None:
return None
name = fid.readline()
# Perform the conversion
number1_inches = float(fid.readline()) / 2.54
number2 = float(fid.readline())
number3 = float(fid.readline())
return (id, name, number1_inches, number2, number3)
with open('filename.txt', 'r') as fid:
records = list()
while True
new_record = read_record(fid)
# Stop if we hit the end of the file
if new_record is None:
break
records.append(new_record)
# Now sort the records based on the value of number1
records = sorted(records, key=lambda x: x[2])
This code is showing only the last item of a list of dictionaries:
def chooseOneServer():
dara = websvc()
i=0
for item in dara:
for key,value in item.items() :
if key == '1' :
servers = ( ('i',value), )
i +=1
return servers
I've already answered this in the comments of your last question, but here it is again:
def chooseOneServer():
dara = websvc()
i=0
servers = []
for item in dara:
for key,value in item.items() :
if key == '1':
servers.append(('i',value))
i += 1
return servers
You just add each item to a list, rather than overwriting the same tuple each time.