因此,有关此问题出现的问题背景,请参阅此link https://stackoverflow.com/questions/48049006/matching-states-and-cities-with-possibly-multiple-words.
正如已接受的答案所建议的那样,我继续使用提供的代码并能够完成我最初想要的。但编一本词典并不是我的最终目标。我使用该字典的最终目标是将其转换为 DataFrame,我能够做到这一点。
这是我所做的:
df = pd.DataFrame(([st, cty] for st, cty in dic.items() for cty in dic[st]),
columns = ["State", "City"])
供您现成参考,dic
变量如下:
{'Alabama': ['Auburn',
'Florence',
'Jacksonville',
'Livingston',
'Montevallo',
'Troy',
'Tuscaloosa',
'Tuskegee'],
'Alaska': ['Fairbanks'],
'Arizona': ['Flagstaff', 'Tempe', 'Tucson'],
'Arkansas': ['Arkadelphia',
'Conway',
'Fayetteville',
'Jonesboro',
'Magnolia',
'Monticello',
'Russellville',
'Searcy'],
'California': ['Angwin',
'Arcata',
'Berkeley',
'Chico',
'Claremont',
'Cotati',
'Davis',
'Irvine',
'Isla Vista',
'University Park, Los Angeles',
'Merced',
'Orange',
'Palo Alto',
'Pomona',
'Redlands',
'Riverside',
'Sacramento',
'University District, San Bernardino',
'San Diego',
'San Luis Obispo',
'Santa Barbara',
'Santa Cruz',
'Turlock',
'Westwood, Los Angeles',
'Whittier'],
'Colorado': ['Alamosa',
'Boulder',
'Durango',
'Fort Collins',
'Golden',
'Grand Junction',
'Greeley',
'Gunnison',
'Pueblo, Colorado'],
'Connecticut': ['Fairfield',
'Middletown',
'New Britain',
'New Haven',
'New London',
'Storrs',
'Willimantic'],
'Delaware': ['Dover', 'Newark'], .... all the other states with their city names
The output that I got after running the above code is as follows (a screenshot):
![enter image description here](https://i.stack.imgur.com/YuXYJ.png)
我的查询是:虽然我得到了所需的输出,并且虽然我制定了“数据帧理解”,可以说,我自己,但我并不完全理解双重for
.
有人可以解释一下具体是如何做的吗for
在另一个里面for
在这种情况下工作。我是熊猫的初学者。