解开不同格式的嵌套列表属性

发布于 2025-01-23 13:29:40 字数 629 浏览 0 评论 0原文

我正在寻找有关如何使用嵌套列表并打开包装的指导。以前,我创建了4个单独的列表来存储用户的响应,其中一个列表存储性别,另一个问题,调查用户的年龄和BMI。

我想尝试通过将调查响应的每个实例嵌套作为嵌套列表来尝试使用单个列表。然后,我需要能够打印出嵌套的列表内容,并最终写入CSV文件。我已经了解了文件I/O要求,我的挑战更多是要迭代嵌套列表以产生以下输出。

由于这是为了一门课程,我正在做一些限制,因为我只能使用列表数据类型存储数据,因此我不能用于loops and sys.stdout.write。

样本列表

records = [["M", "N", 37, 34.67], ["F", "Y", 22, 29.01], ["F", "Y", 88, 24.00]]

输出要求1

["M", "N", 37, 34.67]
["F", "Y", 22, 29.01]
["F", "Y", 88, 24.00]

输出要求2(CSV)

M,N,37,34.67
F,Y,22,29.01
F,Y,88,24.00

I am looking for some guidance on how to work with nested lists and unpacking them. Previously, I had created 4 separate lists to store the responses from users in a survey with one lists storing gender, another a Y/N question, the age and BMI of the survey user.

I want to try and use only a single list by nesting each instance of a survey response as a nested list. I then need to be able to print the nested list contents out and eventually write to a csv file. I already understand the file i/o requirements, my challenge is more about iterating over nested lists to produce outputs like below.

As this is for a course I am doing there are some limitations in that I can only use list data types to store the data, I cannot use for loops and sys.stdout.write is to be used instead of print.

Sample list

records = [["M", "N", 37, 34.67], ["F", "Y", 22, 29.01], ["F", "Y", 88, 24.00]]

Output Requirement 1

["M", "N", 37, 34.67]
["F", "Y", 22, 29.01]
["F", "Y", 88, 24.00]

Output Requirement 2 (CSV)

M,N,37,34.67
F,Y,22,29.01
F,Y,88,24.00

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

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

发布评论

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

评论(1

等风也等你 2025-01-30 13:29:40

这是一个循环的解决方案。

import sys

i = 0
sample  = [["M", "N", 37, 34.67], ["F", "Y", 22, 29.01], ["F", "Y", 88, 24.00]]
while i < len(sample):
    sys.stdout.write(str(sample[i]) + "\n") # 1st form needed
    j = 0
    while j < len(sample[i]):
        sample[i][j] = str(sample[i][j])
        j += 1
    sys.stdout.write(",".join(sample[i]) + "\n") # 2nd form needed
    i += 1

Here is a solution with while loops.

import sys

i = 0
sample  = [["M", "N", 37, 34.67], ["F", "Y", 22, 29.01], ["F", "Y", 88, 24.00]]
while i < len(sample):
    sys.stdout.write(str(sample[i]) + "\n") # 1st form needed
    j = 0
    while j < len(sample[i]):
        sample[i][j] = str(sample[i][j])
        j += 1
    sys.stdout.write(",".join(sample[i]) + "\n") # 2nd form needed
    i += 1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文