Python列表编辑

时间:2017-11-21 10:05:12

标签: python

我必须制作一个程序,要求“登录时间”24次,将所有这些值放入一个列表,然后输出每个登录小时的使用次数,如果键入-1,则会打破循环,例如它有6个输入。

Please enter login hour: 3
Please enter login hour: 4
Please enter login hour: 3
Please enter login hour: 3
Please enter login hour: 4
Please enter login hour: -1
There were 0 logins In hour 0
There were 0 logins In hour 1
There were 0 logins In hour 2 
There were 3 logins In hour 3
There were 2 logins In hour 4
....till 24

这是我到目前为止所做的。我只是不知道如何计算每个元素类型并将它们与其余元素分开。

loginCount = 0
hour = []
for i in range(0,24):
     item = int(input("please enter login hour:")
     hour.append(item)
     if hour[i] == -1
          break
     else: 
          loginCount = loginCount + 1

3 个答案:

答案 0 :(得分:2)

每次都可以使用固定大小的数组并向上计数适当的索引: 由于列表索引从0开始,因此是小时[item-1]。

hour = [0] * 24
for i in range(0,24):
   item = int(input("please enter login hour: "))
   if item == -1:
      break
   else:
      hour[item] += 1

答案 1 :(得分:0)

我添加了一个while循环来计算列表中的元素数量。 希望你不要在列表中添加-1。 包含if语句不附加-1并在用户输入时中断-1 在第二个循环之前,我创建了另一个列表,其中包含来自hour的唯一值,以打印仅针对实际尝试的数字的尝试次数(这与您提到的内容略有不同,您可以将第二个循环中的sorted(unique_hrs)更改为range(1,25))。

hour = []
while len(hour) < 24:
    item = int(input("please enter login hour: "))
    if item != -1:
        hour.append(item)
    else:
        break

unique_hrs = list(set(hour))
for i in sorted(unique_hrs):
    print('There were ' + str(hour.count(i)) + ' logins In hour ' + str(i))

答案 2 :(得分:0)

# We will maintain a list with 24 entries
# Each entry in the list will maintain a count for the number
# of logins in that hour. Finally, we will print all the entries
# from the list that will output number of logins for each hour

# Creating a list with one entry for each hour
records = [0] * 24

# Asking user 24 times
for j in range(0, 24):
    i = int(input("please enter login hour:"))
    # Since lists are mutable, we can increment the count 
    # at the corresponding position of the input hour
    if i != -1:
        records[i - 1] = records[i - 1] + 1
    else:
        break

# Print all the entries from the records
for i in range(len(records)):
    print("There were " + str(records[i]) + " logins in hour " + str(i+1))
相关问题