python中对比数组长度_在Python中检索数组长度的首选方法

python中对比数组长度

The __len__() is a method on container types. However, python also provides another option of retrieving the length of an array, using the method len().

__len __()是关于容器类型的方法。 但是,python还使用len()方法提供了另一个检索数组长度的选项。

The len(abc) usually ends up calling abc.__len__().

len(abc)通常最终会调用abc .__ len __()

Example usage of len() method is as follows,

len()方法的示例用法如下,

# array declaration
test_arr = [1,2,3]

# length
print(len(test_arr))
print(test_arr.__len__())

Output

输出量

3
3

The len() method works on a tuple, string (which are array of characters) in similar way.

len()方法以类似的方式处理元组,字符串(字符数组)。

test_tuple = (1,2,3)

# length
print(len(test_tuple))

# string 
test_str = 'include-help'

# length
print(len(test_str))

Output

输出量

3
12


翻译自: https://www.includehelp.com/python/preferred-way-to-retrieve-the-length-of-an-array.aspx

python中对比数组长度

Python,处理数组长度不一致的问题通常可以通过以下几种方式: 1. 使用内置函数`zip`进行配对处理:`zip`函数可以将多个可迭代对象的对应元素打包成一个元组,然后返回由这些元组组成的列表(在Python 3返回的是一个迭代器)。如果可迭代对象长度不一致,`zip`会在最短的可迭代对象耗尽时停止。 ```python list1 = [1, 2, 3] list2 = [4, 5] list3 = [6, 7, 8, 9] # 使用zip函数配对 for item1, item2, item3 in zip(list1, list2, list3): print(item1, item2, item3) ``` 2. 使用列表推导式和`range`函数进行循环:如果数组长度不一致,可以使用列表推导式和`range`函数来确保循环能够遍历到最长的数组长度。 ```python list1 = [1, 2, 3] list2 = [4, 5] list3 = [6, 7, 8, 9] # 使用列表推导式和range函数处理不等长数组 for i in range(max(len(list1), len(list2), len(list3))): print(list1[i] if i < len(list1) else None, list2[i] if i < len(list2) else None, list3[i] if i < len(list3) else None) ``` 3. 使用`itertools.zip_longest`:`itertools.zip_longest`是Python标准库`itertools`模块的一个函数,它与`zip`类似,但会用指定的填充值填充最短的可迭代对象,从而使得所有可迭代对象达到相同的长度。 ```python from itertools import zip_longest list1 = [1, 2, 3] list2 = [4, 5] list3 = [6, 7, 8, 9] # 使用itertools.zip_longest处理不等长数组 for item1, item2, item3 in zip_longest(list1, list2, list3, fillvalue=None): print(item1, item2, item3) ``` 以上方法可以根据实际情况和个人喜好选择使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值