有什么办法可以用下一个随机数添加前一个随机数吗?

时间:2012-05-20 10:16:40

标签: python random

我有一个数字和alpha的列表混合。

import random

def main():
 list: ['1','2','3','4','5','6','7','a','b','c']

 for count in range (1,5):
   serial_no=("serial #: ", count)
   totallist=0

   from random import choice:
   number=choice(list)

   print(serial_no+'for the time: '+number)

   if number.isdigit() and number<4:
      totallist+=int(number) # want to add the first number >4

   elif number.isdigit()and number>4:
      totallist+=int(number)

   elif number.isalpha():
      list[9]=0
      list[-1]=0
      totallist=int(list[9])+int(list[-1]) #I could not add (error) (want to add alpha(as 0) and number after being alpha)
   print(totallist)

main()  

有什么方法可以将第一个随机数&gt; 4添加到数字的总随机数&lt; 4?

由于

1 个答案:

答案 0 :(得分:1)

我不知道这是不是你想要的,但这就像我可以修复你的语法错误和格式,并猜测你想要实现的目标(希望A努力这里):

import random

def safe_index(li, i):
   try:
      return li[i]
   except:
      return 0

def main():
   list = ['1','2','3','4','5','6','7','a','b','c']
   totallist = []

   for count in range (1,5):
      serial_no = "serial #%s: " % count

      number = random.choice(list)

      print('%s for the time: %s' % (serial_no, number))

      if number.isdigit() and int(number) < 4:
         print('<4')

         # add digit to first number in series >= 4
         totallist.append(int(number) + 
                          safe_index(filter(lambda x: x >= 4, totallist), 0))

      elif number.isdigit() and int(number) >= 4:
         print('>=4')
         totallist.append(int(number))

      elif number.isalpha():
         print('alpha')

         # convert alpha to ordinal number
         totallist.append(ord(number) - (ord('a') - 1))

   print(totallist)

if __name__ == "__main__":
    main()  

示例输出:

serial #1:  for the time: 5
>=4
serial #2:  for the time: 2
<4
serial #3:  for the time: 6
>=4
serial #4:  for the time: a
alpha
[5, 7, 6, 1]