首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将字符串转换为位数组

将字符串转换为位数组
EN

Stack Overflow用户
提问于 2018-12-11 05:23:40
回答 2查看 74关注 0票数 2

我如何才能创建一个Python函数

  • a string
  • a array like this [0, 0, ... 0] (字母表中的每个字母一个零)

并返回

  • 一个新数组,如果单词中出现了相应的字符,则会将0转换为1。

因此,如果一个单词有一个'A''a',并且数组中的第一个点对应于'a',那么输出数组的第一个点就会有一个1

[1, ...]

如果一个单词有一个'B''b',那么输出数组的第二个点将有一个1。如果一个单词有一个'a'和一个'b',那么输出数组的第一个和第二个点就会有一个1

[1, 1, ...]

诸若此类。因此,字符串"abba"的结果如下所示:

[1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

理想情况下,我还可以搜索不在字母表中的字符,比如!?,并且只需在数组中添加其他位来表示这些字符。

欢迎任何帮助!非常感谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-12-11 05:32:18

创建此类列表的一种非常简单的方法是:

def string_to_bit_array(text):
    # We don't care if upper or lower case
    text = text.lower()
    # Remove duplicate alphabet characters
    text = set(text)
    # Define alphabet characters
    alphabet = "abcdefghijklmnopqrstuvwxyz"
    # Create list with zeros
    matches = [0] * len(alphabet)
    # Loop over every character of the text
    for character in text:
        # Skip this character if not in alphabet
        if not character in alphabet:
            continue
        # Find index of character in alphabet
        index = alphabet.find(character)
        # Set match index to one instead of zero
        matches[index] = 1
    # Return result
    return matches

print(string_to_bit_array("abba"))

这将打印:

[1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

如果需要,您可以向alphabet中添加更多字符:

alphabet = "abcdefghijklmnopqrstuvwxyz!?"
票数 2
EN

Stack Overflow用户

发布于 2018-12-11 05:45:50

为什么不创建一个简单的映射字典

import string
alphabet=string.ascii_lowercase
d=dict(zip(alphabet,range(0,26)))
a=[0]*26

字典将如下所示

{'a': 0,
 'b': 1,
 'c': 2,
 'd': 3,
 'e': 4,
 'f': 5,
 'g': 6,
 'h': 7,
 'i': 8,
 'j': 9,
 'k': 10,
 'l': 11,
 'm': 12,
 'n': 13,
 'o': 14,
 'p': 15,
 'q': 16,
 'r': 17,
 's': 18,
 't': 19,
 'u': 20,
 'v': 21,
 'w': 22,
 'x': 23,
 'y': 24,
 'z': 25}

查找和更新列表的逻辑

for i in set('aabbc?'):
    index_to_update=d.get(i,None)
    if index_to_update is not None:
        a[index_to_update]=1
print(a)#[1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53713846

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档