我如何才能创建一个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]
理想情况下,我还可以搜索不在字母表中的字符,比如!
和?
,并且只需在数组中添加其他位来表示这些字符。
欢迎任何帮助!非常感谢。
发布于 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!?"
发布于 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]
https://stackoverflow.com/questions/53713846
复制相似问题