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

发布于 2024-11-19 15:18:37 字数 689 浏览 1 评论 0原文

今天,根据我在这里得到的答案,我编写了这段小代码来创建一个包含 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. 将这 2 个列表作为列放入制表符分隔 (txt) 文件中,一个紧挨着另一个,以便轻松地将它们复制粘贴到 Excel 文件中。我研究了 csv 模块,但它似乎只有行的方法。

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 > 100:
            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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

醉态萌生 2024-11-26 15:18:37

如果您正在寻找一种更有效的方法来从源中获取每个列表元素 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')

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')
你的心境我的脸 2024-11-26 15:18:37

像这样的东西应该有效:
(我对这两个列表稍微调整了你的程序,但试图保持一般的“要点”相同)

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

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'))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文