简体   繁体   English

将数组转换为0和1

[英]Converting an array to 0s and 1s

Suppose I have an array A = [13, 15, 17] . 假设我有一个数组A = [13, 15, 17] I want to create a new array B such that all entries apart from its 13th, 15th and 17th entries are 0 , and each of these three are 1 's. 我想创建一个新的数组B ,使得除了第13,15和17条之外的所有条目都是0 ,并且这三个中的每一个都是1 How can I do this? 我怎样才能做到这一点?

Use a list comprehension: 使用列表理解:

B = [int(i+1 in A) for i in range(max(A))]

For each number in the range from 0 to the highest number in A , we take int(i+1 in A) . 对于从0A最高数字的每个数字,我们取int(i+1 in A) i+1 in A will be a boolean value. i+1 in A将是一个布尔值。 If that number is in A , the result will be True . 如果该数字在A ,则结果为True Otherwise it will be False . 否则它将是False Since bool inherits from int , we can easily convert it to a normal integer with int() . 由于bool继承自int ,我们可以使用int()轻松将其转换为普通整数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM