python读取数组长度_arr .__ len __()是在Python中获取数组长度的首选方法吗?

In Python, is the following the only way to get the number of elements?

arr.__len__()

If so, why the strange syntax?

解决方案my_list = [1,2,3,4,5]

len(my_list)

# 5

The same works for tuples:

my_tuple = (1,2,3,4,5)

len(my_tuple)

# 5

And strings, which are really just arrays of characters:

my_string = 'hello world'

len(my_string)

# 11

It was intentionally done this way so that lists, tuples and other container types or iterables didn't all need to explicitly implement a public .length() method, instead you can just check the len() of anything that implements the 'magic' __len__() method.

Sure, this may seem redundant, but length checking implementations can vary considerably, even within the same language. It's not uncommon to see one collection type use a .length() method while another type uses a .length property, while yet another uses .count(). Having a language-level keyword unifies the entry point for all these types. So even objects you may not consider to be lists of elements could still be length-checked. This includes strings, queues, trees, etc.

The functional nature of len() also lends itself well to functional styles of programming.

lengths = map(len, list_of_containers)

读取输出数据 # 读取train.hdf5文件的二维数组 with h5py.File('train001.hdf5', 'r') as f: data01 = f['increment_4/phase/alpha-Ti/mechanical/O'][:] data02 = f['/increment_4/phase/alpha-Ti/mechanical/epsilon_V^0.0(F)_vM'][:] data02 = data02[:, np.newaxis] data03 = f['/increment_4/phase/alpha-Ti/mechanical/sigma_vM'][:] data03 = data03[:, np.newaxis] data03 = data03 / 1e6 # 归一化到-1和1之间 data03 = (data03 - np.max(data03) / 2) / (np.max(data03) / 2) # 按行连接数组 arr = np.hstack((data01, data02, data03)) # 每1024行提取出来作为一个二维数组 output_arr_reshaped = arr.reshape((-1, 1024, 6)) # 将每个二维数组转换成三维数组 output_arr_3d = [] for i in range(output_arr_reshaped.shape[0]): output_arr_3d.append(np.reshape(output_arr_reshaped[i], (32, 32, 6))) # 将每个三维数组转换成6 * 32 * 32的三维数组 output_arr_6_32_32 = [] for i in range(len(output_arr_3d)): output_arr_6_32_32.append(np.transpose(output_arr_3d[i], (2, 0, 1))) # 对每个5 * 32 * 32的数组进行修改 modified_output_arr = [] for i in range(len(output_arr_6_32_32)): output_arr_i = output_arr_6_32_32[i] output_arr_i = np.array(output_arr_i) output_arr_i = torch.from_numpy(output_arr_i).float() output_arr_i = output_arr_i.unsqueeze(0) modified_output_arr.append(output_arr_i) # 输出第一个三维数组的第一个纵向二维数组 output_arr01 = modified_output_arr[0] 帮我优化这段代码,使得这段代码功能完全不变的情况下更加精简,并帮我标好每一段的功能
05-10
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值