在 Python 的 for 循环中使用多个变量

编程入门 行业动态 更新时间:2024-10-28 12:16:23
本文介绍了在 Python 的 for 循环中使用多个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图更深入地了解 for 如何在 Python 中针对不同数据类型进行循环.使用 for 循环迭代数组的最简单方法是

for i in range(len(array)):do_something(数组[i])

我也知道我可以

for i in array:做某事(一)

我想知道这是做什么

for i, j in range(len(array)):# 这里的 i 和 j 是什么?

对于数组中的 i, j:# 在这种情况下,i 和 j 是什么?

如果我尝试对 dictionaries 或 tuples 使用相同的想法会发生什么?

解决方案

最简单最好的方法是第二个,而不是第一个!

for i in array:做某事(一)

永远不要这样做,它会不必要地使代码复杂化:

for i in range(len(array)):do_something(数组[i])

如果您出于某种原因需要数组中的索引(通常您不需要),请改为这样做:

for i, enumerate(array) 中的元素:打印(使用索引",我)做某事(元素)

这只是一个错误,当你试图将一个整数解包成两个名字时,你会得到TypeError: 'int' object is not iterable:

for i, j in range(len(array)):# 这里的 i 和 j 是什么?

这个可能有效,假设数组是二维的":

对于数组中的 i, j:# 在这种情况下,i 和 j 是什么?

二维数组的一个例子是一对列表:

>>>对于 i, j 在 [(0, 1), ('a', 'b')]:...打印('我:',我,'j:',j)...i: 0 j: 1我:a j:b

注意: ['these', 'structures'] 在 Python 中称为列表,而不是数组.

I am trying to get a deeper understanding to how for loops for different data types in Python. The simplest way of using a for loop an iterating over an array is as

for i in range(len(array)): do_something(array[i])

I also know that I can

for i in array: do_something(i)

What I would like to know is what this does

for i, j in range(len(array)): # What is i and j here?

or

for i, j in array: # What is i and j in this case?

And what happens if I try using this same idea with dictionaries or tuples?

解决方案

The simplest and best way is the second one, not the first one!

for i in array: do_something(i)

Never do this, it's needlessly complicating the code:

for i in range(len(array)): do_something(array[i])

If you need the index in the array for some reason (usually you don't), then do this instead:

for i, element in enumerate(array): print("working with index", i) do_something(element)

This is just an error, you will get TypeError: 'int' object is not iterable when trying to unpack one integer into two names:

for i, j in range(len(array)): # What is i and j here?

This one might work, assumes the array is "two-dimensional":

for i, j in array: # What is i and j in this case?

An example of a two-dimensional array would be a list of pairs:

>>> for i, j in [(0, 1), ('a', 'b')]: ... print('i:', i, 'j:', j) ... i: 0 j: 1 i: a j: b

Note: ['these', 'structures'] are called lists in Python, not arrays.

更多推荐

在 Python 的 for 循环中使用多个变量

本文发布于:2023-07-26 07:01:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1214850.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   变量   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!