简体   繁体   English

如何允许用户脱离字典理解能力?

[英]How do I allow the user to break out of a dictionary comprehension?

I was playing with a simple dictionary comprehension code, and have altered it to allow for automatically generated keys (sequential numbers, which can be swapped out by way of code if desired) and user input for the values. 我在玩一个简单的字典理解代码,并对其进行了更改,以允许自动生成键(顺序号,如果需要,可以通过代码交换出来)和用户输入的值。 I also have it to where the user can input the keys and the values. 我也有用户可以在其中输入键和值的地方。

My problem is figuring out how to allow the user to break out of it; 我的问题是弄清楚如何让用户脱离它。 ie, if they choose 100 for the number of entries, but find they only need 27, there needs to be a way to enter a command to end the process. 也就是说,如果他们选择100作为条目数,但发现它们仅需要27,则需要一种输入命令以结束该过程的方法。

The third example is where I tried putting a condition on the end, but failed to figure it out. 第三个例子是我试图在最后放置一个条件,但没有弄清楚。 I knew it wouldn't work when I did it - it allows the user to go through one run. 我知道当我这样做时它是行不通的-它允许用户进行一次运行。

"""
Example 1:
Auto-generated sequential numerical keys with user input for values:
"""

variable1=int(input("please select number of entries: ")) 

d1 = {x : input("Provide data: ") for x in range(1,variable1 + 1)}

"""
Example 2:
User input for keys and values:
"""
variable1=int(input("please select number of entries: ")) 

d1 = {input("Please provide key: "): input("Please provide data: " for x in range(1,variable1 + 1)}


"""
Example 3:
This shows where I tried to put the condition, which failed:
"""
variable1=int(input("please select number of entries: ")) 

d1 = {x : input("Provide data: ") for x in range(1,variable1 + 1) if x != 0}

You should not be using a dictionary comprehension here. 您不应该在这里使用字典理解。 Could you? 您可以...吗? Sure. 当然。 Is it going to help you learn stuff as a new user to Python? 它将帮助您以Python的新用户身份学习知识吗? No. 没有。

Take for example chepner's answer. 以chepner的答案为例。 It probably works. 它可能有效。 I'm not going to test it. 我不会去测试。 Is it readable and easy to understand? 它易读易懂吗? Maybe. 也许。 If your goal is to get a job, a lot of people look for more than just a right answer. 如果您的目标是找到一份工作,那么很多人寻求的不仅是正确的答案。 There are many, many, many ways to get a right answer. 有很多很多方法可以找到正确的答案。 If your answer is hard to comprehend for an interviewer, I would definitely think about writing the answer differently. 如果您的面试官很难理解您的答案,那么我肯定会考虑改写答案。 I would recommend taking a look at sub-reddits for interview/programming help as well. 我建议您也查看一下子Reddits,以获取面试/编程帮助。 You may also want to take a look at cracking the coding interview for preparing for technical interviews since they are very different from a normal interview. 您可能还想看看如何破解编码面试,以准备进行技术面试,因为它们与常规面试有很大不同。

In terms of your actual question: 根据您的实际问题:

    In [54]: d1 = {}
    ...: for i in range(variable1):
    ...:     data = input('provide data:')
    ...:     if data =='x':
    ...:         break
    ...:     else:
    ...:         data = int(data)
    ...:     d1[i+1] = data
    ...:
    ...:
provide data:12
provide data:13
provide data:14
provide data:x

In [55]: d1
Out[55]: {1: 12, 2: 13, 3: 14}

This will cycle up to variable1 , but if the user provides x , the loop will break. 这将循环到variable1 ,但是如果用户提供x ,则循环将中断。 Just because something can be done in one line doesn't mean it should ;) 仅仅因为可以在一行中完成某件事并不意味着就应该这样做;)

The 2-argument form of iter will call a function until it returns a particular variable. iter的2参数形式将调用一个函数,直到返回特定变量为止。 Specifically, iter(input, "0") will produce a stream of non-zero integer strings, which you can zip with your range: 具体来说, iter(input, "0")将产生一个非零整数字符串流,您可以使用范围zip它:

d1 = {x : y for x, y in zip(
                            range(1,100),
                            iter(lambda: input("Provide data "), "0")
                        )
}

Or, use enumerate to generate an infinite stream of numbered calls to input which you can filter with islice : 或者,使用enumerate生成无限数量的input调用,您可以使用islice进行过滤:

from itertools import islice


d1 = {x: y for x, y in islice(
                           enumerate(
                               iter(lambda: input("Provide data "), "0"),
                               1
                           ),
                           100
                       )
}

In either case, because you have an unfiltered stream of tuples, you can pass that directly to dict instead of using a comprehension. 在这两种情况下,由于您都有未过滤的元组流,因此可以直接将其传递给dict而无需使用理解。

d1 = dict(zip(range(1,100), iter(lambda: input("Provide data "), "0")))
d1 = dict(islice(enumerate(iter(lambda: input("Provide data "), "0"), 1), 100))

For those that (justifiably) dislike the Lisp-like nature of all the nested function calls, you can easily break this into several lines for readability. 对于那些(合理地)不喜欢所有嵌套函数调用的类似Lisp的性质的用户,您可以轻松地将其分成几行以提高可读性。 For example, 例如,

responses = iter(lambda: input("Provide data "), "0")
d1a = dict(zip(range(1,100), responses))
d1b = dict(islice(enumerate(responses, 1)), 100)   

Or, if you prefer a traditional loop: 或者,如果您喜欢传统循环:

d = {}
for k in range(1, 100):  # or itertools.count(1) for unbounded input
    v = input("Provide data ")
    if v == "0":
        break
    d[k] = v

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

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