r/pythonhelp • u/Strange-Performer-78 • Dec 04 '21
HOMEWORK inquiries about python
Hello, this is my first post on this subreddit. I just wanted to know how to append items to a list which correspond to each other. For example I have 3 people input their names and the amount of property they sold, how do I add it to the list in a way that they get stored individually under the same index.
2
Upvotes
2
u/Goobyalus Dec 04 '21
Here are some options
# I'm using this data instead of grabbing input each time
def input_generator():
"""
A proxy for getting input data
"""
simulated_inputs = (
"John",
"25",
"Joseph",
"10",
"Mary",
"15",
)
for data in simulated_inputs:
yield data
def list_method():
# Ignore this, and pretend next(inputs) is an `input` call.
inputs = input_generator()
print()
print("List Method")
print("="*80)
# Empty list to store data on individual realtors
result = []
# Populate our list with sublists
# We will represent individual realtors as lists like: [name, property_sold]
for i in range(3):
name = next(inputs)
property_sold = int(next(inputs))
result.append([name, property_sold]) # Note that you could just as easily use a normal tuple here
# Print the sublist of the second realtor
print(result[1])
# Print the 3rd realtor's info formatted
print(result[2][0], "sold", result[2][1], "properties.")
# Print the entire result
print(result)
# Output
"""
List Method
================================================================================
['Joseph', 10]
Mary sold 15 properties.
[['John', 25], ['Joseph', 10], ['Mary', 15]]
"""
return result
def parallel_lists_method():
# Ignore this, and pretend next(inputs) is an `input` call.
inputs = input_generator()
print()
print("Parallel Lists Method")
print("="*80)
# Empty lists to store name and properties sold
names = []
properties_sold = []
# Populate our lists with data
for i in range(3):
names.append(next(inputs))
properties_sold.append(int(next(inputs)))
# Print the info of the second realtor
print(names[1], properties_sold[1])
# Print the 3rd realtor's info formatted
print(names[2], "sold", properties_sold[2], "properties.")
# Print the entire result (combined into a tuple)
result = (names, properties_sold)
print(result)
# Output
"""
Parallel Lists Method
================================================================================
Joseph 10
Mary sold 15 properties.
(['John', 'Joseph', 'Mary'], [25, 10, 15])
"""
return result
def named_tuple_method():
from collections import namedtuple
# Ignore this, and pretend next(inputs) is an `input` call.
inputs = input_generator()
print()
print("Named Tuple Method")
print("="*80)
# Define a named tuple for realtor data
Realtor = namedtuple("Realtor", ["name", "property_sold"])
# Empty list to store our named tuples
result = []
# Populate our list with named tuples
for i in range(3):
name = next(inputs)
property_sold = int(next(inputs))
result.append(Realtor(name, property_sold))
# Print the named tuple of the second realtor
print(result[1])
# Print the 3rd realtor's info formatted
print(result[2].name, "sold", result[2].property_sold, "properties.")
# Print the entire result
print(result)
# Output
"""
Named Tuple Method
================================================================================
Realtor(name='Joseph', property_sold=10)
Mary sold 15 properties.
[Realtor(name='John', property_sold=25), Realtor(name='Joseph', property_sold=10), Realtor(name='Mary', property_sold=15)]
"""
return result
def dict_method():
# Ignore this, and pretend next(inputs) is an `input` call.
inputs = input_generator()
print()
print("Dict Method")
print("="*80)
# Empty list to map realtor names to amount of property sold
result = {}
# Populate our dict
for i in range(3):
name = next(inputs)
property_sold = int(next(inputs))
result[name] = property_sold
# Print Joseph's data
print(result["Joseph"])
# Print Mary's info formatted
print("Mary", "sold", result["Mary"], "properties.")
# Print the entire result
print(result)
# Output
"""
Dict Method
================================================================================
10
Mary sold 15 properties.
{'John': 25, 'Joseph': 10, 'Mary': 15}
"""
return result
def class_method():
# Ignore this, and pretend next(inputs) is an `input` call.
inputs = input_generator()
print()
print("Class Method")
print("="*80)
# Define class to represent realtors
class Realtor:
def __init__(self, name, property_sold=None):
"""
Initializer for Realtor instances.
"""
self.name = name
self.property_sold = property_sold
def __str__(self):
"""
Override default __str__ method to return something descriptive.
"""
return f"Realtor {self.name} sold {self.property_sold} properties."
# Empty list to store Realtor instances
result = []
# Populate our dict
for i in range(3):
name = next(inputs)
property_sold = int(next(inputs))
result.append(Realtor(name, property_sold))
# Print second realtor object
print(result[1])
# Print third realtor's info
print(result[2].name, "sold", result[2].property_sold, "properties.")
# Print the entire result
print(result)
# Output
"""
Class Method
================================================================================
Realtor Joseph sold 10 properties.
Mary sold 15 properties.
[<__main__.class_method.<locals>.Realtor object at 0x000002C3D0F47940>, <__main__.class_method.<locals>.Realtor object at 0x000002C3D0F478E0>, <__main__.class_method.<locals>.Realtor object at 0x000002C3D0F47670>]
"""
return result
if __name__ == "__main__":
functions = (
list_method,
parallel_lists_method,
named_tuple_method,
dict_method,
class_method,
)
results = {function.__name__: function() for function in functions}
print()
print("All results")
print("="*80)
for function_name, result in results.items():
print(f"{function_name}:")
print(result)1
u/structurefall Dec 04 '21
In the case you're describing, you might want to make each in the list a dict.
yourlist = [{"name": "Some Guy", "amount": 1234}, {"name": "Other Guy", "amount": 4321}]
1
u/CraigAT Dec 04 '21
You could use a "list of lists" or a "nested list" (different terms for the same thing).
Effectively your "inner" list is the name of 1 person and the amount of properties they sold, then the "outer" list is a list of those individual lists (or pairs).