如何将布尔数组转换为字符串表示形式?

时间:2019-08-20 17:35:30

标签: python arrays python-2.7 hash

我想像这样转换imagehash个布尔数组:

array([[False, False, False,  True, False, False,  True,  True],
       [False, False, False,  True,  True,  True,  True,  True],
       [False,  False, False,  True,  True,  True,  True,  True],
       [False,  True,  True,  True,  True,  True,  True,  True],
       [False,  True,  True,  True,  True,  True, False, False],
       [False,  True,  True,  True,  True,  True,  True, False],
       [False, False,  True, False, False, False,  True, False],
       [False, False, False, False, False, False,  True,  True]]))

使用Python 2.7转换为94b1b9fcfcfcf0f0之类的字符串表示形式,反之亦然。

我该如何实现?

1 个答案:

答案 0 :(得分:1)

以下代码将您的布尔值转换为0/1并从这些数字获取十六进制值(8个二进制数字最多提供2个十六进制字符(从00到ff)。dt[, paste0("outcome", 1:2) := lapply(.SD, function(x) str_detect(product.3, str_replace_all(x, ",", "|"))), .SDcols = c('product.2', 'stock')] dt[, outcome3 :=unlist(Map(function(x, y) { x1 <- sort(x[!is.na(x)]) y1 <- sort(y[!is.na(y)]); length(intersect(x1, y1)) == length(x1)}, str_extract_all(product.3, "[A-Z]"), str_extract_all(stock, "[A-Z]"))) & !is.na(product.3)] for(j in names(dt)[5:6]) set(dt, i = which(is.na(dt[[j]])), j = j, value = FALSE) dt # product stock product.2 product.3 outcome1 outcome2 outcome3 # 1: A A B C FALSE FALSE FALSE # 2: B A,B C A,C,E TRUE TRUE FALSE # 3: C A,B,C A,C,E A,B TRUE TRUE TRUE # 4: A,C,E A,B,C,E A,B A,B,C TRUE TRUE TRUE # 5: A,B A,B,C,E A,B,C D FALSE FALSE FALSE # 6: A,B,C A,B,C,E D A FALSE TRUE TRUE # 7: D A,B,C,D,E A B FALSE TRUE TRUE # 8: A A B A FALSE TRUE TRUE # 9: B A,B A A TRUE TRUE TRUE #10: A A,B A A,B,C TRUE TRUE FALSE #11: A A A,B,C D FALSE FALSE FALSE #12: A,B,C A,B,C D D TRUE FALSE FALSE #13: D A,B,C,D D <NA> FALSE FALSE FALSE #14: D A,B,C,D <NA> <NA> FALSE FALSE FALSE 用于填充左侧如果数字小于128,则返回零。zfill去除十六进制表示形式([2:])。

0x

P.S。此解决方案仅包含纯Python-hexstring = "".join([str(hex(int("{}".format("".join(["1" if elem else "0" for elem in line])), 2)))[2:].zfill(2) for line in array]) print(hexstring) 变量包含一个列表列表:

array