简体   繁体   English

从字典创建列表

[英]Creating a list from a dictionary

I'm trying to teach myself python so I apologize if the question itself doesn't make much sense.我正在尝试自学 python 所以如果问题本身没有多大意义,我深表歉意。

I am doing the examples of an online introductory to Python course I am sitting in on and the prompt is to write a code to read through a file and find all emails before adding them to a dictionary before printing out the person who had sent the most emails and the number they sent.我正在做 Python 课程的在线介绍示例,我正在上课,提示是编写代码来阅读文件并查找所有电子邮件,然后再将它们添加到字典中,然后打印出发送最多的人电子邮件和他们发送的号码。 My issue is that the prompt specifically asks for this to be done by sorting through the list in reverse order.我的问题是提示特别要求通过以相反顺序对列表进行排序来完成此操作。

I managed to get the same end result simply by parsing out the names and then counting each time it popped up before finding the largest value and printing that out with the corresponding key in a for loop.我设法通过解析名称,然后计算每次弹出的名称,然后找到最大值并在 for 循环中使用相应的键打印出来,就得到了相同的最终结果。 However I was unsure if this is what I was supposed to do or if the book was asking for something else.但是我不确定这是否是我应该做的,或者这本书是否要求别的东西。 Does the dictionary itself count as a list?字典本身算作列表吗?

for k,v in di.items():
   if largest_so_far ==-1
      largest_so_far = v
   elif v > largest_so_far :
      largest_so_far = v
      the_word = k

print(the_word,largest_so_far)

This is the code I used to print out the person with name emails.这是我用来打印姓名电子邮件的人的代码。 I tried changing我试着改变

for k,v in di.items():

into进入

for k,v in reversed(di.items()):

in order to try and at least get some semblance of printing it out in reversed order but the code ran normally with no changes or issues.为了尝试并至少以相反的顺序打印出来,但代码运行正常,没有任何更改或问题。

Again, I apologize if this doesn't make much sense.再次,如果这没有多大意义,我深表歉意。 I am almost entirely self taught(only able to watch prerecorded videos and read the text book) and am still trying to attain even a basic understanding of this language.我几乎完全是自学成才(只能观看预先录制的视频和阅读教科书),并且仍在努力获得对这种语言的基本理解。

The for loop as written will always end up with whatever it finds to be the largest v in the dictionary.所写的for循环总是以它发现的字典中最大的v结束。 As such reversed(...) just changes the order in which it checks all the elements of the dictionary, but usually won't change what you see in the print() statement.因此reversed(...)只会更改检查字典所有元素的顺序,但通常不会更改您在 print() 语句中看到的内容。

Putting a statement inside the for loop might help your debugging, eg print(word, largest_so_far) immediately after the elif block and indented at exactly the same level as the elif .for循环中放置一个语句可能有助于您的调试,例如print(word, largest_so_far)紧跟在elif块之后,并且缩进与elif完全相同的级别。

(I assume you have a statement largest_so_far = -1 prior to the for loop. Consider changing it to largest_so_far = None and then use if not largest_so_far: within the for loop.) (我假设您在for循环之前有一条语句largest_so_far = -1 。考虑将其更改为largest_so_far = None ,然后在 for 循环中使用if not largest_so_far: 。)

If I understand correctly, what you're really asking is why the book says to sort a list and get the last element (ie max element) instead of just finding the max element.如果我理解正确,那么您真正要问的是为什么书中说要对列表进行排序并获取最后一个元素(即最大元素),而不是仅仅找到最大元素。 If that's correct, then your way to do it is actually better.如果这是正确的,那么你的做法实际上更好。 It's wasteful to sort a list when all you need is the largest element.当您只需要最大元素时,对列表进行排序是很浪费的。 This is not a big problem for small datasets (less than, say, 10000 items), but for larger datasets, it would start to get noticeable.对于小型数据集(例如,少于 10000 个项目),这不是一个大问题,但对于较大的数据集,它会开始变得明显。 This is because finding the largest element just requires looping once, which in big-O notation is O(n) , while sorting requires looping at least once and possibly doubling back a few times, meaning its worst-case performance is O(n log n) , which is worse than O(n) by a bit.*这是因为找到最大的元素只需要循环一次,在大 O 表示法中是O(n) ,而排序需要循环至少一次并且可能加倍返回几次,这意味着它的最坏情况下的性能是O(n log n) ,这比O(n)差一点。*


By the way, if you want to consider a more advanced tool to do the same job, you can use max() with a key function :顺便说一句,如果您想考虑使用更高级的工具来完成相同的工作,您可以使用max()和键 function

max(di.items(), key=lambda kv: kv[1])

Or for keeping a dict of items-to-occurrences, you could use a Counter , which has some handy methods built in like most_common() .或者为了保持项目出现的字典,你可以使用Counter ,它有一些内置的方便方法,比如most_common()


* Implementation detail for CPython : max() actually is slower than list.sort() due to the overhead of the iterator protocol . * CPython 的实现细节由于迭代器协议的开销, max()实际上list.sort()慢。 There's no special case for dict_items or other native data types. dict_items或其他本机数据类型没有特殊情况。 (Reference: source code (current tip of master branch) .) To see an actual performance difference, you'd want to look at types that don't have a built-in .sort() method, or types implemented in C with a built-in .max() method like NumPy's ndarray . (参考: 源代码(master 分支的当前提示) 。)要查看实际的性能差异,您需要查看没有内置.sort()方法的类型,或者在 C 中实现的类型一个内置的.max()方法,比如 NumPy 的ndarray

İf you want to sort values from higher to lower you can this method:如果您想将值从高到低排序,您可以使用以下方法:

sorted_list = sorted(di.values(), reverse = True)

In this way you can get list of sorted dictionary values通过这种方式,您可以获得排序字典值的列表

Then you can use values as you want.然后,您可以根据需要使用值。 Good luck:)祝你好运:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM