【问题标题】:Is there a way to call an item in a list each time using a for loop?有没有办法每次使用 for 循环调用列表中的项目?
【发布时间】:2019-04-13 23:51:06
【问题描述】:

我想打印一个句子,让列表中的每个项目生成一个新句子。如果可能的话,我也希望在使用列表理解时能够做到这一点。

我尝试浏览所有资源,但没有成功。

>>>squared = [17, 100, 25]
>>>my_iterator = iter(squared)

>>>for multiplied in iter(squared):
...    x = next(my_iterator) ** 2
...    print("The square of {0} in list 'squared' is {}".format(???, x)

我应该放什么??? (在上面的打印行中)。我想说: “列表 'squared' 中 17 的平方是 298” “列表 'squared' 中 100 的平方是 10000 ETC... 列表理解可以做同样的事情吗?

>>>new_squared = [i **2 for i in squared]
print(???)

我尝试过放置 .format(my_iterator, x) 但唯一弹出的是内存分配或其他东西......并且 .format(next(my_iterator), x) 不起作用。

【问题讨论】:

  • multiplied 代替???
  • 哇...就这么简单...谢谢。

标签: python list for-loop list-comprehension


【解决方案1】:

我不确定你在问什么。你只是在找这个吗?

squared = [17, 100, 25]

for x in squared:
    print("The square of {} in list 'squared' is {}".format(x, x ** 2))

输出:

The square of 17 in list 'squared' is 289
The square of 100 in list 'squared' is 10000
The square of 25 in list 'squared' is 625

【讨论】:

  • 是的。谢谢。
猜你喜欢
  • 2023-03-04
  • 2021-07-14
  • 1970-01-01
  • 2011-04-30
  • 1970-01-01
  • 2020-08-23
  • 1970-01-01
  • 1970-01-01
  • 2022-11-17
相关资源
最近更新 更多