繁体   English   中英

Python列表编辑

[英]Python list editing

我必须编写一个要求“登录小时” 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

您可以每次使用固定大小的数组并向上计数适当的索引:由于列表索引从0开始,所以它是hour [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

我添加了一个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))
# 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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM