- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
假设我有这个嵌套字典:
d = {'Ben': {'wo_mana': ['Strength = 1.10', 'Speed = 1.50'], 'wi_mana': ['Int = 1.20'], 'Skill': 'true', 'Magic': 'false'},
'Tom': {'wi_mana': ['Int = 1.40'], 'wo_mana': ['Agility = 1.60'], 'Skill': 'true', 'Magic': 'true'}}
键和值不是我自己定义的,它们实际上是从文件中提取的数据。
Skill
和 Magic
的值的数量是固定的,即 1。
但是,wo_mana
和wi_mana
的取值个数不固定,可以是1、2、3、4等。
在上面的示例中,wo_mana
对于 Ben
有 2 个值。
我的目标是将其打印在表格中(用选项卡分隔),当在 Excel 中打开时,它看起来像这样:
Name Skill Magic wo_mana wi_mana
Ben true false Strength = 1.10 Int = 1.20
Speed = 1.50
Tom true true Agility = 1.60 Int = 1.40
请注意,对于每个人,wo_mana
和 wi_mana
列可以有多行。
我尝试使用csv
模块,我的代码:
import csv, itertools
header = ['Name', 'Skill', 'Magic', 'wo_mana', 'wi_mana']
with open('output.csv', 'w') as f:
w = csv.DictWriter(f, header)
w.writeheader()
for key, val in sorted(d.items()):
row = {'Name': key}
row.update(val)
w.writerow(row)
我的输出:
Name,Skill,Magic,wo_mana,wi_mana
Ben,true,false,"['Strength = 1.10', 'Speed = 1.50']",['Int = 1.20']
Tom,true,true,['Agility = 1.60'],['Int = 1.40']
所以看起来不适合使用csv
打印多行部分
那么也许我必须使用字符串格式
?有谁知道如何打印这样的表格?任何帮助将不胜感激。
最佳答案
给你(已编辑):
import csv, itertools
d = {'Ben': {'wo_mana': ['Strength = 1.10'], 'wi_mana': ['Int = 1.20'], 'Skill': 'true', 'Magic': 'false'},
'Tom': {'wi_mana': ['Int = 1.40'], 'wo_mana': ['Agility = 1.60'], 'Skill': 'true', 'Magic': 'true'}}
header = ['Name', 'Skill', 'Magic', 'wo_mana', 'wi_mana']
with open('output.csv', 'w') as f:
w = csv.DictWriter(f, header)
w.writeheader()
for key, val in sorted(d.items()):
row = {'Name': key}
# print val
wo_mana = [item for item in val['wo_mana']]
wi_mana = [item for item in val['wi_mana']]
val['wo_mana'] = wo_mana[0]
val['wi_mana'] = wi_mana[0]
row.update(val)
w.writerow(row)
dict_list = []
if len(wi_mana) > len(wo_mana):
for index, item in enumerate(wo_mana):
dict_ = {}
dict_['wi_mana'] = wi_mana[index]
dict_['wo_mana'] = wo_mana[index]
# print dict_
dict_list.append(dict_)
[dict_list.append({'wi_mana': item}) for item in wi_mana[len(wo_mana):]]
else:
for index, item in enumerate(wi_mana):
dict_ = {}
dict_['wi_mana'] = wi_mana[index]
dict_['wo_mana'] = wo_mana[index]
# print dict_
dict_list.append(dict_)
[dict_list.append({'wo_mana': item}) for item in wo_mana[len(wi_mana):]]
# print dict_list
if len(dict_list) > 1:
[w.writerow(dict_) for dict_ in dict_list[1:]]
这有效!让我知道。
编辑:根据问题:
However, the number of values for wo_mana and wi_mana is unfixed, which can be 1, 2, 3, 4 etc.
所以我假设不会出现 KeyError。根据评论中的修改语句这里是解决方案:
它没有针对各种条件进行正确测试,根据我从评论中了解到的内容,它工作正常,如果有任何问题,请告诉我:
import csv, itertools
d = {'Ben': {'Skill': 'true', 'Magic': 'false'},
'Tom': {'wo_mana': ['Strength = 1.10'], 'wi_mana': ['Int = 1.20', 'O_o'], 'mana': ['Int = 1.20', 'dsadas', 'whatever', '-_-'], 'Skill': 'true', 'Magic': 'true'}}
header = ['Name', 'Skill', 'Magic', 'wo_mana', 'wi_mana', 'mana']
with open('output.csv', 'w') as f:
w = csv.DictWriter(f, header)
w.writeheader()
for key, val in sorted(d.items()):
row = {'Name': key}
# print val
row.update(val)
dictionary_containing_list = {key: val[key] for key in val if type(val[key])==list}
if dictionary_containing_list:
max_length = len(max(dictionary_containing_list.iteritems(), key=lambda x: len(x[1]))[1])
dict_list = []
for i in range(max_length):
dict_ = {}
for key, val_list in dictionary_containing_list.iteritems():
try:
dict_[key] = val_list[i]
except IndexError:
pass
dict_list.append(dict_)
row.update(dict_list[0])
print dict_list
w.writerow(row)
if dictionary_containing_list:
[w.writerow(dict_) for dict_ in dict_list[1:]]
该解决方案非常通用,您可以添加任意数量的mana
/列,它就会起作用。请记住将准确的列名称附加到 header
列表中!
关于Python:如何将嵌套字典打印为具有可变行的复杂表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38115533/
我之前发布过question已得到答复,但我也需要对此进行查询。我有一个包含这样数据的表结构(日期格式为 dd/mm/yyyy)。 ID Account Number Unit Ad
我正在使用 React Native Calendars 并尝试为议程组件构建我的数据。 预期的数据结构是(一个对象) { '2012-05-22': [{text: 'item 1 - any j
这个问题不太可能对任何 future 的访客有帮助;它只与一个较小的地理区域、一个特定的时间点或一个非常狭窄的情况相关,通常不适用于全世界的互联网受众。如需帮助使此问题更广泛适用,visit the
两列城镇和优先级。 我需要对表进行排序,以便优先级=1的城镇排在第一位,并且不按名称 ASC 排序,而其余城镇则按名称 ASC 排序。 我该怎么做? 谢谢;) 更新 SELECT * FROM map
我有三个表“Hardware_model”、“Warehouse”和“Brand”,并且表以这种方式一起引用:Hardware_model 仓库Hardware_model 品牌 现在我要执行以下
我有一个 MySQL 表 (tbl_filters),包含 3 列:id、cat、val id 和 val 是数字,cat 是 varchar。每个 id 有多行。 我还有另一个包含多个列的表 (tb
我想获取字段的不同值,比方说:field1...这需要一个如下查询:“从表中选择不同的(字段1)” 但是,对于某些记录,field1 为空,并且还有另一列可以替代 field1,即 field2。对于
表 1 - 用户 id username items 1 Paul 1(0020);2(0001); 表 2 - 项目 id name 1 name_here 在我的用户的项目中,我输入了 2(000
我想连接同一个表 4 次以获取列的显示方式,我不确定是否可以在 1 个 SQL 语句中完成。 tbl_用户名 id username 1 Adam 2 Bob 3 Chris tbl_机
首先,我刚刚开始自己学习JS,没有任何编程经验,这意味着我仍然要了解这种出色的编程语言的基本构建模块。 我的问题与我编写的以下代码有关: let orderCount = 0; con
关闭。这个问题需要details or clarity .它目前不接受答案。 想改进这个问题吗? 通过 editing this post 添加细节并澄清问题. 关闭 9 年前。 Improve t
我正在使用 XMAPP,MySQL 正在正常运行。在 phpMyAdmin 中,我不太明白这一点,所以我尝试在 PHP 中创建一个。使用此代码,它会告诉我数据库 benutzer。尽管我在 phpMy
是否有一种高效的算法可以找到平均度最大的子图(可能是图本身)? 最佳答案 The paper "Finding a Maximum-Density Subgraph" by Andrew Goldbe
目录 1、业务背景 2、场景分析 3、流程设计 1、业务流程 2、导入流程
我有 2 个表: 1) 包含自 1900 年 1 月 1 日以来所有日期的 Masterdates 表 2) Stockdata 表,其中包含表单中的股票数据 日期、交易品种、开盘价、最高价、最低价、
我有一个非常复杂的 UI,其状态栏不断变化,其中包含多种类型的状态消息,并且 UI 具有复杂的图表控件和已加载的指示性地理 map 。 现在这些小而复杂的区域的数据上下文具有同样复杂的 ViewMod
有人可以用简单的方式向我解释为什么常量在大 O 表示法中无关紧要吗?为什么添加常量时复杂性保持不变。这不是作业问题,我只是想更好地理解这一点。让我明白这个大 O 是为了看到一个函数在接近无穷大时的行为
我在 flex 搜索索引中有以下文档。 [{ "_index": "ten2", "_type": "documents", "_id": "c323c
我有一个以零碎的方式构建的 LINQ 查询,如下所示: var initialQuery = from item in MyContext where xxx == yyy select item;
我目前正在涉足 SQL,并且希望针对我所创建的问题获得一些帮助。 为了练习一些编程,我正在制作一个 IOU 应用程序。下面是我存储的表我的借条记录(忽略一些相关栏目)。该表允许用户说“嘿,你欠我 X
我是一名优秀的程序员,十分优秀!