I am writing a program that generates a list of integer coordinates for all points in the first quadrant from (1, 1) to (5, 5)

huangapple go评论115阅读模式
英文:

I am writing a program that generates a list of integer coordinates for all points in the first quadrant from (1, 1) to (5, 5)

问题

I have to use list comprehension which I don't know how to use because I have just started learning Python. It displays the error message:

TypeError: 'int' object is not iterable

So this is the code I have currently written:

  1. frst_quadrant = 1
  2. for a in frst_quadrant:
  3. a =+ 1
  4. if a > 5:
  5. break
  6. elif a < 5:
  7. a =+ 1
  8. print(a)
  9. continue
  10. else:
  11. a =+ 1
  12. print(a)
  13. continue

Please help me solve this problem.

英文:

And I have to use list comprehension which i dont how to use because i have just started learning python
It displays the error message

  1. TypeError: &#39;int&#39; object is not iterable

so this is the code i have currently written

  1. frst_quadrant = 1
  2. for a in frst_quadrant:
  3. a =+ 1
  4. if a &gt; 5:
  5. break
  6. elif a &lt; 5:
  7. a =+ 1
  8. print(a)
  9. continue
  10. else:
  11. a =+ 1
  12. print(a)
  13. continue

Please help me solve this problem

答案1

得分: 0

第一行中,你将first_quadrant写成了一个整数1。第二行中,你尝试在一个整数上使用for循环。这是不允许的,因此会出现错误。

你可以用很多其他方法来做这个。我写了两种可能的解决方案。

解决方案1

  1. first_quadrant = 1
  2. last_quadrant = 5
  3. coordinates = []
  4. for x in range(first_quadrant, last_quadrant + 1, 1):
  5. for y in range(first_quadrant, last_quadrant + 1, 1):
  6. coordinates.append([x, y])
  7. print(coordinates)

解决方案2

  1. coordinates = [[x, y] for x in range(1, 5 + 1, 1) for y in range(1, 5 + 1, 1)]
  2. print(coordinates)
英文:

In the first line you have written first_quadrant as 1 which is an integer. In the second line you are trying to use a for loop over an integer. This is not allowed and therefore the error.

You could do it in many other ways. I am writing two such possible solutions.

Solution 1

  1. first_quadrant = 1
  2. last_quadrant = 5
  3. coordinates = []
  4. for x in range(first_quadrant,last_quadrant +1, 1):
  5. for y in range(first_quadrant,last_quadrant +1, 1):
  6. coordinates.append([x,y])
  7. print(coordinates)

Solution 2

  1. coordinates = [[x,y)] for x in range(1, 5+1,1) for y in range(1, 5+1, 1)]
  2. print(coordinates)

huangapple
  • 本文由 发表于 2020年1月7日 01:42:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/59616605.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定