1—Python first experience of generating random arrays and writing to files

Hits: 0

First contact with Python to complete a process of generating [random numbers] and writing to a file:

  • Generate a random array tmp[]
  • Count the number of occurrences of each number in a random array
  • Write random arrays to the file .dat file one per line

'''
Generate an array of 0s and 1s and write it to the .dat file
'''

import random                                # import random function

print( 'Please enter the length of the array' )
length = int(input())                        # The input of input is a character, which needs to be converted to an integer
tmp = []
for i in range(length):
    tmp.append(random.randint(0, 1)) 
myset = set(tmp)                             # myset is another list, which contains no duplicate items in tmp 
print( 'item\t\tnum' )
 for item in myset:
  print("%d\t\t\t%d" % (item, tmp.count(item)))
with open('D:/UECode/PythonScript/bit.dat', 'w') as bit_box:
    for i in range(length):
        bit_box.write(str(tmp[i]))
        bit_box.write( '\n' )                  # Newline every time a bit is printed

without duplicates-1 Reference link for statistics without duplicates-2 Reference link
for file reading and writing

After Python is so light, is it not necessary to open the cumbersome MATLAB, and run UltraEdit directly under the editor to
configure the Python runtime environment link

You may also like...

Leave a Reply

Your email address will not be published.