如何将列表导出到Excel兼容文件中?

时间:2011-07-11 17:18:01

标签: python excel python-3.x text-files

今天,根据我在这里得到的答案,我写了这个小代码来创建一个包含16个元素的随机列表。

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 > 100:
            result = [random.choice(sources)]

print(result)

现在我想做的是: 1.创建2个随机列表,以不同的方式命名它们(如何根据for循环计数器执行此操作?) 2.将这两个列表作为列放在制表符分隔(txt)文件中,一个紧挨着另一个,以便轻松地将它们复制粘贴到Excel文件中。我查看了csv模块,但它似乎只有行的方法。

2 个答案:

答案 0 :(得分:1)

如果您正在寻找一种更有效的方法来从源中获取每个列表元素中的4个随机排序列表,请尝试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']

接下来,你想根据循环计数器生成并命名列表...我建议不要这样做。相反,只需将随机列表一次附加到列表中,您就可以按照附加顺序对它们进行索引。

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

但是这仍然会让您遇到数据存在于两个单独列表中的问题。要解决此问题,您需要zip()功能。它将列表1中的每个元素与列表2中相应的索引元素连接起来,在每个索引处形成一个元组。这可以使用任意数量的序列来完成。

>>> 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')]

要将列表中的列表压缩在一起,请在元列表名称前使用*星形解包运算符。

>>> my_data = zip(*rand_lists)

现在要输出到csv文件;只需编写自己的csv函数就足够了。请记住,列分隔符是逗号,行分隔符是换行符。

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

从这里只需将您的压缩列表组合传递到out_csv函数,并确保您的文件名具有.csv扩展名。 Excel可以原生地读入.csv个文件,因此您不需要进行任何复制粘贴。

这是最后一步:

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

答案 1 :(得分:0)

这样的事情应该有效: (我为2个列表略微调整了你的程序,但试图保持一般“gist”相同)

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'))
相关问题