-2

数字とアルファのリストが混在しています。

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()  

数<4の合計乱数に最初の乱数>4を追加する方法はありますか?

ありがとう

4

1 に答える 1

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]
于 2012-05-20T10:51:54.683 に答える