开发者

how do I export my lists into an excel compatible file?

开发者 https://www.devze.com 2023-03-19 05:39 出处:网络
Today, on the basis of answers I got here, I wrote this little code to create a random list of 16 elements.

Today, on the basis of answers I got here, I wrote this little code to create a random list of 16 elements.

import random

sources = ['Prone', 'Supine', 'Halfway', 'HalfInv']
result = [random.choice(sources)]
repeats = 0
fail = 0

while len(result) < 16:
    elem = random.choice(sources)
    repeats = result.count(elem)
    print(repeats)
    if (elem != result[-1]) & (repeats < 4):
        result.append(elem)
    else:
        fail = fail + 1
        print(fail)
        if fail > 开发者_如何学JAVA100:
            result = [random.choice(sources)]

print(result)

Now what I'd like to do is: 1. to create 2 random lists naming them differently (how do I do this based on the for loop counter?) 2. put those 2 lists as columns in a tab delimited (txt) file, one next to the other in order to easily copy paste them in an excel file. I looked into csv module but it seems to only have methods for rows.


If you're looking for a more efficient way to get a randomly ordered list of 4-of-each of your list elements from sources, try random.shuffle(list):

>>> import random
>>> random.seed()
>>> sources = ['Prone', 'Supine', 'Halfway', 'HalfInv']
>>> copy1 = sources * 4
>>> copy2 = sources * 4
>>> copy1 == copy2
True
>>> random.shuffle(copy1)
>>> random.shuffle(copy2)
>>> copy1 == copy2
False
>>> copy1
['HalfInv', 'Prone', 'Halfway', 'Supine', 'Prone', 'Halfway', 'Prone', 'Supine', 'Prone', 'HalfInv', 'HalfInv', 'Halfway', 'Supine', 'Halfway', 'HalfInv', 'Supine']
>>> copy2
['Prone', 'Halfway', 'Prone', 'Prone', 'HalfInv', 'Halfway', 'Halfway', 'HalfInv', 'Supine', 'HalfInv', 'Halfway', 'Supine', 'Prone', 'Supine', 'HalfInv', 'Supine']

Next, you wanted to generate and name the lists based on the loop counter... I'd recommend against this. Instead just append your random lists into a list one at a time, and you can index them in the order they were appended.

>>> n = 2 # number of random lists you want
>>> rand_lists = [] # A list for holding your randomly generated lists
>>> for i in range(n):
    sources_copy = sources * 4
    random.shuffle(sources_copy)
    rand_lists.append(sources_copy)

But this still leaves you with the problem that your data is in two separate lists. To remedy this you want the zip() function. It joins each element in list 1 with its correspondingly indexed element in list 2, forming a tuple at each index. This can be done with an arbitrary number of sequences.

>>> list1 = [1,2,3,4,5]
>>> list2 = ['a','b','c','d','e']
>>> zip(list1, list2)
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]

To zip together your lists-within-a-list, use the * star unpacking operator before the name of your meta-list.

>>> my_data = zip(*rand_lists)

Now you want to output to a csv file; it's easy enough to just write your own csv function. Remember that the column delimiters ate commas, the row delimiters are newlines.

def out_csv(mydata, filename):
    with open(filename, 'w') as out_handle:
        for line in mydata:
            out_handle.write(','.join(line) + '\n')

From here just pass your zipped list combo into the out_csv function, and make sure your filename has the .csv extension. Excel can natively read in .csv files so you shouldn't need to do any copy-pasting.

Here's the last step:

>>> out_csv(my_data, 'my_name.csv')


Something like this should work: (I tweaked your program a little for the 2 lists, but tried to keep the general "gist' the same)

import random

sources = ['Prone', 'Supine', 'Halfway', 'HalfInv']
#result = [random.choice(sources)]
result = {1:[], 2:[]}
#repeats = 0
#fail = 0

for part in result:
    fail = 0
    repeats = 0
    while len(result[part]) < 16:
        elem = random.choice(sources)
        repeats = result[part].count(elem)
        print(repeats)
        if (not result[part]) or ((elem != result[part][-1]) & (repeats < 4)):
            result[part].append(elem)
        else:
            fail = fail + 1
            print(fail)
            if fail > 100:
                result[part] = []

print(result)



with open('somefile.csv','wb') as f:
    #f.write('\r\n'.join('%s\t%s' % (a,b) for a, b in zip(result[1], result[2])))
    f.write(bytes('\r\n'.join('%s\t%s' % (a,b) for a, b in zip(result[1], result[2])), 'UTF-8'))
0

精彩评论

暂无评论...
验证码 换一张
取 消