如何保存来自“for”的值循环? Python 3 [英] How to save values from a "for" loop? Python 3

查看:1013
本文介绍了如何保存来自“for”的值循环? Python 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

昨天我发布了一个问题,我正在寻找一种方法来为 循环执行无限 ,而不使用 完全可以(因为我的老师需要这样做),而且我们也不能使用任何我们从未见过的命令类)。这显然很困难,因为显然没有一个非常可行的选项没有使用,或者其他函数如 itertools 或.append等。



您可以在这里 a>

另外,非常感谢你们给我带来的反馈! :)






我设法与我的老师交谈,我们获得了许可使用 itertools 或者只是一个足够大的范围(而不是实际上是无限的)。




我已经解决了一些练习,但现在我有以下的指令:


(考虑 成绩

•向用户询问一个数字(,通过输入), 继续询问 ,直到用户告知停止。

•然后,根据输入的所有数字计算平均值


(其实它稍微复杂一点,但我缩短了它,我相信我可以处理其余的问题)。 b
$ b

正如我所说的,必须 循环使用,并且I 不能使用 whiles



如果我可以使用 'd做这样的事情:

  def grades():
totalg = 0
countg = 0
keepAdding =y
while(keepAdding ==y):
qualifle = int(input(插入等级,范围从0到100)
totalg = totalg + qualif
countg = countg + 1
keepAdding = str(input(您是否希望增加数据?(y / n)))
print(The你的平均成绩是,totalg / countg)

我该怎么做,但是 用于 循环?我不知道如何存储数据以供以后计算。






另外,我很想知道更多正确的方式来结束循环,但我不能使用 break



预先感谢!任何建议表示赞赏和欢迎! :)

解决方案

一种方法是在没有外部模块的情况下使用 two-arg iter ;当传递两个参数时,第一个是一个无参数函数来反复调用,第二个是标记值,而不是指示您应该停止。



例如,你可以用一些简单的东西来做一个无限循环:

  for _ in iter(bool,True):

由于 bool 构造函数返回 False True 的标记值永远不会发生,所以这是一个无限循环。



类似地,为了让一个循环提示,直到用户响应一个给定的sentinel字符串,比如'q'退出(或者只是空字符串),你可以做:

  inp in iter(lambda:input(插入等级,范围从0到100('q'退出)),'q'):
val = int(inp)
...循环的其余部分...

很明显,这有点模糊(两个参数 iter 很少见),所以通常是y你可以使用,而True:,循环包含test-and - break 或者test-and - return (后者不违反老师要求的字母)。同样的,异常处理可以用来退出循环,虽然它很丑陋:

  try:
for ... :
如果test_for_end:
提升StopIteration
,除了StopIteration:
传递
#你在循环之外

注意:除了实际的,True:循环外,一个测试 - < - c $ c> break / 返回的情况。但是你有一只手绑在背后,所以我建议用一些可怕的突变手来代替。


Yesterday I posted a question where I was searching for a way to do an infinite for loop, without using while at all (because my teacher wants so, and also, we can't use any commands we haven't seen in class). It was difficult as apparently there wasn't a very viable option that didn't use while, or other functions like itertools or .append, etc.

You can see that question here
Also, thanks a lot for the feedback you guys brought me! :)


But I managed to talk with my teacher and we got permission to use itertools or just a range big enough (instead of actually infinite).


I solved a few exercises already, but now I have the following instructions:

(Think about grades)
• Ask the user a number (through inputs), and keep asking until the user tells to stop.
• Then, calculate the average from all the numbers entered.

(It's actually a little more complex, but I shortened it and I believe I can deal with the rest)

As I said, I must use a for loop, and I can't use whiles at all.

If I could use while, I'd do something like this:

def grades():
    totalg = 0
    countg = 0
    keepAdding = "y"
    while(keepAdding == "y"):
        qualif = int(input("Insert grades obtained, in scale from 0 to 100 "))
        totalg = totalg + qualif
        countg = countg + 1
        keepAdding = str(input("Do you wish to keep adding data? (y/n) "))
    print("The average of your grades is", totalg/countg)

How can I do something like that, but with for loops? I have no idea on how to store the data for later calculation.


Also, I'm interested into knowing a more "proper" way to be able to end the loop, but I can't use a break neither.

Thanks in advance! Any advice is appreciated and welcome! :)

解决方案

One way to do this is, without outside modules, is to use two-arg iter; when passed two arguments, the first is a no-argument function to call over and over, and the second is a sentinel value than indicates you should stop.

So for example, you could make an infinite loop with something as simple as:

 for _ in iter(bool, True):

Since the bool constructor returns False, a sentinel value of True will never occur, so that's an infinite loop.

Similarly, to make a loop that prompts until the user responds with a given sentinel string, like 'q' for quit (or just the empty string), you could do:

for inp in iter(lambda: input("Insert grades obtained, in scale from 0 to 100 (type 'q' to quit)"), 'q'):
    val = int(inp)
    ... rest of loop ...

Obviously, this is a little obscure (two-arg iter is rarely seen), so usually you'd use while True: with the loop containing a test-and-break or test-and-return (the latter doesn't violate the letter of the teacher's requirements). Similarly, exception handling can be used to exit the loop, though it's ugly:

 try:
     for ...:
         if test_for_end:
             raise StopIteration
 except StopIteration:
     pass
 # You're outside the loop

Note: Literally everything I've mentioned is terrible style, aside from an actual while True: loop with a test-and-break/return case. But you've got one hand tied behind your back, so I'm suggesting some terrible mutant hands to substitute.

这篇关于如何保存来自“for”的值循环? Python 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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