在python中获得一半的浮动

时间:2018-12-01 12:26:27

标签: python list slice

我有一个<form class="row" name="regform" action = "<?php echo base_url()?>user/login" method="POST"> <input type="hidden" name="ref" value=1> <div class="col-md-6 col-lg-3"> <input type="email" name="email" placeholder="Email Address"> </div> <div class="col-md-6 col-lg-3"> <input type="password" name="password" placeholder="Any Password"> </div> <div class="col-md-6 col-lg-3"> <button type="submit" class="btn btn--primary type--uppercase" name="signup" value="signup" formaction = "<?php echo base_url()?>user/register">Signup</button> </div> <div class="col-md-6 col-lg-3"> <button type="submit" class="btn btn--primary type--uppercase" name="signin" value="signin" formaction = "<?php echo base_url()?>user/login">Signin</button> </div> </form> 的大整数列表。我想将它们2乘2并切成两半。例如,我必须将10 digits(list = [1010101010, 1111000110,1111000111,1111000101]...)与list [1]分组,然后将每半分割。 list[0]的{​​{1}}的前一半将是我要保存并以后使用的数字。如何将整数切成两半,而只使用它们的一半? 我设法将元素按2进行分组,但是我不知道如何拆分和合并它们。

list[0]+last

2 个答案:

答案 0 :(得分:1)

您可以将int转换为字符串,然后进行切片:

lst = [1010101010, 1111000110, 1111000111, 1111000101]
out = [lst[k:k+2] for k in range(0,len(lst), 2)]

result = [int(str(first)[:5] + str(second)[5:]) for first, second in out]
print(result)

输出

[1010100110, 1111000101]

更新

如果输入是numpy数组,则应这样做:

import numpy as np
np.random.seed(42)

lst = np.random.randint(2, size=(50, 10))
out = [lst[k:k+2] for k in range(0,len(lst), 2)]
result = [int(''.join(map(str,  first[:5].tolist() + second[5:].tolist()))) for first, second in out]
print(result)

输出

[100001110, 1011101000, 11111000, 11101, 101011110, 111110110, 1010000000, 1011110101, 11110000, 10011100, 100101010, 11111101, 1010000110, 100010101, 1110111001, 1110001, 1011110011, 101001100, 1001011010, 1110011110, 1100100111, 1110111100, 101101100, 1010110101, 1101000101]

请注意,此解决方案通过将值转换为int来删除前导零。

答案 1 :(得分:-1)

n = 2
out = [sum([kk/2 for kk in list[k:k+n]]) for k in range(0,len(list),n)]