使用raw_input进行操作

时间:2014-07-19 13:14:49

标签: python list python-2.7 dictionary

我有5个整数的列表。

它们是在数小时内观察到的流星数量。

# Nights = [11pm,12pm,1am,2am,3am]
mon = [2,4,1,3,2]
tue = [3,2,4,3,3]
wed = [1,2,1,1,1]
thu = [4,3,2,3,4]
fri = [2,1,2,1,1]

我想使用raw_input向我询问一个晚上和一个时间,然后它会将值返回给我。

night = raw_input('Which night? mon,tue,wed,thu or fri. ')
time = raw_input('Which time? t11,t12,t01,t02 or t03. ')
t11,t12,t01,t02,t03 = 0,1,2,3,4
print night[time]

这里的问题是'night'raw_input是一个字符串,不能用于夜晚[时间]

TypeError: cannot concatenate 'str' and 'float' objects

我该怎么做?

4 个答案:

答案 0 :(得分:7)

您可以将与天相对应的流星事件存储为字典,例如

occurrences = dict(
    mon = [2, 4, 1, 3, 2],
    tue = [3, 2, 4, 3, 3],
    wed = [1, 2, 1, 1, 1],
    thu = [4, 3, 2, 3, 4],
    fri = [2, 1, 2, 1, 1]
)

同样可以将时间存储为字典

times = dict(
    t11 = 0
    t12 = 1,
    t01 = 2,
    t02 = 3,
    t03 = 4
)

现在,只需从times获取索引并从occurrences获取并显示它们,就像这样

night = raw_input('Which night? mon,tue,wed,thu or fri. ')
time = raw_input('Which time? t11,t12,t01,t02 or t03. ')
print occurrences[night][times[time]]

答案 1 :(得分:4)

night只是一个字符串,而不是具有相同名称的变量。将这些列表放在字典中:

nights = {
    'mon': [2,4,1,3,2],
    'tue': [3,2,4,3,3],
    'wed': [1,2,1,1,1],
    'thu': [4,3,2,3,4],
    'fri': [2,1,2,1,1],
}

现在你可以映射到那个来获取每晚。您还需要一个适合您时代的类似字典:

times = {'t11': 0, 't12': 1, 't01': 2, 't02': 3, 't03': 4}

现在您可以使用这些地图映射到nights结构:

night = raw_input('Which night? mon,tue,wed,thu or fri. ')
time = raw_input('Which time? t11,t12,t01,t02 or t03. ')
print nights[night][times[time]]

您还可以使用collections.namedtuple() object为时间条目命名:

from collections import namedtuple

NightEntry = namedtuple('NightEntry', 't11 t12 t01 t02 t03')

nights = {
    'mon': NightEntry(2,4,1,3,2),
    'tue': NightEntry(3,2,4,3,3),
    'wed': NightEntry(1,2,1,1,1),
    'thu': NightEntry(4,3,2,3,4),
    'fri': NightEntry(2,1,2,1,1),
}

现在每个条目都有将名称映射到值的属性; nights['mon'].t11'mon'之夜的第一个条目; 2

然后,您可以使用getattr()使用动态属性访问权限,或者使用namedtuple._asdict() method将属性作为字典访问:

night = raw_input('Which night? mon,tue,wed,thu or fri. ')
time = raw_input('Which time? t11,t12,t01,t02 or t03. ')

# using getattr
print getattr(nights[night], time)

# using a dictionary
print nights[night]._asdict()[time]

答案 2 :(得分:2)

times = ['t11','t12','t01','t02','t03']
vars()[night][times.index(time)]

我们首先按字符串名称查找正确的变量,然后将时间名称映射到列表索引。

答案 3 :(得分:1)

尝试:

# Nights = [11pm,12pm,1am,2am,3am]
meteors = [[2,4,1,3,2],[3,2,4,3,3],[1,2,1,1,1],[4,3,2,3,4],[2,1,2,1,1]]

night = raw_input('Which night? mon,tue,wed,thu or fri. ')
time = raw_input('Which time? t11,t12,t01,t02 or t03. ')
night_string = ['mon', 'tue', 'wed', 'thu', 'fri']
time_string =['t11','t12','t01','t02','t03']
print meteors[night_string.index(night)][time_string.index(time)]