如何获得该程序以打印列表中列表的内容?

时间:2019-05-28 22:16:45

标签: python

我仍然是python的初学者,但是最近我一直在尝试使其变得更好。我正在尝试创建一个程序,询问用户今天是什么日子以及他们必须做什么。然后它将把它放在一个列表中。我正在尝试使该程序打印出具有新任务的列表,但是它不起作用。 (具有该任务的列表在另一个列表中。)

我试图将它们全部放在函数中并使用return stmt,但是它说“对象不可调用”。我还尝试了使用print stmt将其正常打印出来,但这是行不通的。

#List of days
doa = ["M","T","W","TH","F","S","SU"]

#Lists for every day
my_list = []
for i in range(7):
    my_list.append([i])

#Ask user what today is
day = input("What is the day today?")

#Ask user assignment
ast = input("What do you have to do my sir?")

#Add to list
if day == doa[i]:
    my_list[i].append(ast)

#Print that days list to check
print(my_list(day))

我知道我在做什么错了。我假设我正在执行的方式会打印出列表的索引(在另一个列表中)...,但是我想不出其他任何方式。

4 个答案:

答案 0 :(得分:1)

我假设用户当天输入了TH,因此您可以使用list.index获取当天的索引,并使用该索引进行追加和打印。

doa = ["M","T","W","TH","F","S","SU"]

my_list = []
for i in range(7):
    my_list.append([i])

day = input("What is the day today?")
day_index = doa.index(day)

ast = input("What do you have to do my sir?")

my_list[day_index].append(ast)

print(my_list[day_index])

答案 1 :(得分:0)

您可以用字典替换列表,然后使用输入来更新字典。

这里是Add keys to Dict的一个很好的例子。

答案 2 :(得分:0)

您当然可以使用列表来执行此操作。您访问列表中变量的方法甚至设置列表列表的方法都可能使您失望。

>>> doa = ["M","T","W","TH","F","S","SU"]
>>> my_list = [[day] for day in doa]
>>> my_list
[['M'], ['T'], ['W'], ['TH'], ['F'], ['S'], ['SU']]
>>> day = input("What is the day today?")
What is the day today?M
>>> ast = input("What do you have to do my sir?")
What do you have to do my sir?Too much 
>>> for d in my_list:
...     if d[0] == day:
...         d.append(ast)
... 
>>> my_list
[['M', 'Too much'], ['T'], ['W'], ['TH'], ['F'], ['S'], ['SU']]

可能更好的方法是使用字典。通过提供对列表的命名访问,可以简化您的代码(通常效率更高)。

>>> doa = ["M","T","W","TH","F","S","SU"]
>>> my_list = {day: [] for day in doa}
>>> my_list
{'M': [], 'T': [], 'W': [], 'TH': [], 'F': [], 'S': [], 'SU': []}
>>> day = input("What is the day today?")
What is the day today?M
>>> day
'M'
>>> ast = input("What do you have to do my sir?")
What do you have to do my sir?Too much
>>> ast
'Too much'
>>> my_list[day].append(ast)
>>> my_list[day]
['Too much']
>>> my_list
{'M': ['Too much'], 'T': [], 'W': [], 'TH': [], 'F': [], 'S': [], 'SU': []}

答案 3 :(得分:0)

此方法无需对代码进行重大更改:

#List of days
doa = ["M","T","W","TH","F","S","SU"]

#Lists for every day
my_list = []
for i in range(7):
    my_list.append([])

#Ask user what today is
day = input("What is the day today?")

#Ask user assignment
ast = input("What do you have to do my sir?")

#Add to list
my_list[doa.index(day)].append(ast)

#doa.index(day) is the the position of "day" in the list doa

#Print that days list to check
print(my_list[doa.index(day)])