Python:如何将枚举元素用作字符串? [英] Python: How can I use an enumerate element as a string?

查看:101
本文介绍了Python:如何将枚举元素用作字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我正在枚举的 dict1.keys() 列表,我想将该元素用作字符串.

I have a list of dict1.keys() I'm enumerating over and I'd like to use the element as a string.

for i,j in enumerate(dict1.keys()): str(j) = somethingElse
>>> SyntaxError: can't assign to function call

https://dbader.org/blog/python-enumerate 描述枚举实体作为元组:(索引,元素).type(j),我可以打印,但不能用作变量.

https://dbader.org/blog/python-enumerate describes the enumerate entities as a tuple of: (index, element). The type(j) is <class 'str'>, which I can print, but not use as a variable.

for i,j in enumerate(dict1.keys()): j = somethingElse

我认为问题可能出在熊猫身上.第一行有效,第二行无效.

I think the problem may be with pandas. The first line works, not the second.

for i,j in enumerate(dict1.keys()): list1.append(j)
for i,k in enumerate(list1): k = pd.DataFrame(dict1[k]['Values'])

第二行确实有效,但仅以一个 df 结尾,名称为k"而不是键.但继承人什么林试图.每个 dict 使用其键名转换为 df:

That second line does work, but only for only ends up with one df, with name 'k' instead of the key. But heres what Im trying to. Each dict converted to a df using its key name:

for i,j in enumerate(dict1.keys()): j = pd.DataFrame(dict1[j]['Values'])

根据下面的评论,我切换到键上的 for 循环(不需要显式调用),但它仍然不会使用元素 'i' 作为变量.但是,从下面链接的问题来看,元素可以用作字典中的键.在将问题简化为使用列表项作为数据框的名称"并搜索该问题后,它变了.我也会发布作为答案:

According to the comments below, I switched to a for loop on the keys (which dont need to be explicitly called), but it still won't use the element 'i' as a variable. However, from the question linked below, elements are able to be used as a key in a dict. After reducing the question to "use list item as name for dataframe" and searching that, it verks. I'll post as an answer also:

dict2={}
for i in dict1: dict2[i] = pd.DataFrame(dict1[i]['Values'])

..因此保留了名称.实际上,这类似于 Sheri 对列表的回答,但名称保留与 dfs 的关联.可能没有办法使用普通字符串以外的东西来设置变量值,但我会开始一个不同的 问题.

..thus the names are preserved. Actually, this is similar to Sheri's answer with lists, but the names retain association with the dfs. There may not be a way to set a variable value using something other than a plain string, but I'll start a different question for that.

使用列表中的元素作为数据框名称

推荐答案

因为您是在 for 循环内动态生成 Pandas 数据帧,所以在最后打印 j 时,它会显示最后一个生成的数据框.您应该将数据框存储在列表中尝试使用:

Because you are generating your pandas dataframe dynamically inside a for loop so at the end when you print j it will show you the last generated dataframe. You should store your dataframe in list Try using this:

listOfFrame = [] 
for j in dict.keys(): 
    j = pd.DataFrame(dict[j]['Values'])
    listOfFrame.append(j)

这篇关于Python:如何将枚举元素用作字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆