小编jed*_*jed的帖子

Python:从列表创建字典并自动生成/增加键(列表是实际的键值)?

我已经很努力地搜索了,但找不到与我想要的完全相关的问题。

我有一个名为“words”的文件,它有大约 1000 行随机 AZ 排序的单词......

10th
1st
2nd
3rd
4th
5th
6th
7th
8th
9th
a
AAA
AAAS
Aarhus
Aaron
AAU
ABA
Ababa
aback
abacus
abalone
abandon
abase
abash
abate
abater
abbas
abbe
abbey
abbot
Abbott
abbreviate
abc
abdicate
abdomen
abdominal
abduct
Abe
abed
Abel
Abelian
Run Code Online (Sandbox Code Playgroud)

我正在尝试将此文件加载到字典中,其中使用的词是键值,键实际上是每个词的自动生成/自动递增

例如{0:10th, 1:1st, 2:2nd} ...等等...等等...

下面是我到目前为止一瘸一拐的代码,它似乎有点工作,但它只向我显示文件中的最后一个条目作为唯一的 dict 对元素

f3data = open('words')

mydict = {}

for line in f3data:
    print line.strip()
    cmyline = line.split()
    key = +1
    mydict [key] = cmyline

print …
Run Code Online (Sandbox Code Playgroud)

python file-io dictionary

5
推荐指数
1
解决办法
1万
查看次数

有没有办法在不使用operator.itemgetter的情况下对嵌套列表进行排序?

我有一个文件,我正在读,然后创建嵌套列表,我想然后排序4元素(zipcode)

jk43:23 Marfield Lane:Plainview:NY:10023
axe99:315 W. 115th Street, Apt. 11B:New York:NY:10027
jab44:23 Rivington Street, Apt. 3R:New York:NY:10002
ap172:19 Boxer Rd.:New York:NY:10005
jb23:115 Karas Dr.:Jersey City:NJ:07127
jb29:119 Xylon Dr.:Jersey City:NJ:07127
ak9:234 Main Street:Philadelphia:PA:08990
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

ex3_3 = open('ex1.txt')
exw = open('ex2_sorted.txt', 'w')

data = []
for line in ex3_3:
    items = line.rstrip().split(':')
    data.append(items)
print sorted(data, key=operator.itemgetter(4))
Run Code Online (Sandbox Code Playgroud)

输出:

[['jb23', '115 Karas Dr.', 'Jersey City', 'NJ', '07127'], ['jb29', '119 Xylon Dr.', 'Jersey City', 'NJ', '07127'], ['ak9', '234 Main Street', 'Philadelphia', 'PA', '08990'], ['jab44', '23 …
Run Code Online (Sandbox Code Playgroud)

python sorting nested-lists

1
推荐指数
1
解决办法
3087
查看次数

标签 统计

python ×2

dictionary ×1

file-io ×1

nested-lists ×1

sorting ×1