【问题标题】:Transform string into a bit array将字符串转换为位数组
【发布时间】:2019-05-11 20:03:42
【问题描述】:

我怎样才能创建一个 Python 函数呢

  • 一个字符串
  • 这样的数组[0, 0, ... 0](每个字母一个零)

然后返回

  • 一个新数组,如果它们各自的字符出现在单词中,则将零转换为一。

因此,如果一个单词有'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]

理想情况下,我还可以搜索不在字母表中的字符,例如 !?,然后将其他位添加到数组中以表示这些字符。

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

【问题讨论】:

  • 您是要求优化还是只是要求任何蛮力方法来做到这一点。如果进行优化,请展示您的蛮力解决方案。否则,请帮助我们估计您需要帮助的级别。你能打个招呼吗?你能得到输入吗?可以输出吗?你能设置一个像要填充的数组吗?如果其中任何一个是肯定的,请出示您的代码。

标签: python arrays string sorting


【解决方案1】:

创建这样一个列表的一个非常简单的方法是:

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!?"

【讨论】:

  • 谢谢!非常感激。感谢您离开 cmets。我只是在学习编码,所以更容易理解。
【解决方案2】:

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

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]

【讨论】:

  • 谢谢!我最终没有选择这个选项,因为我不想导入新模块。
  • @XaviPi 没关系。 Python 充满了使您的生活更轻松并使您的代码更具可读性的模块。享受编码:)
猜你喜欢
  • 1970-01-01
  • 2022-12-09
  • 2017-11-27
  • 2011-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多