从回文到非回文的字典?
dictionary with palindromes to non palindromes?
很抱歉,如果这太简单了,但我不知道如何构建这本词典。
例如我有一个字符串
"Bob and Anna are meeting at noon"
我想要一个字典,其中所有回文都指向以下非回文的列表,所以
{"Bob": ["and"], "Anna": ["are", "meeting", "at"], "noon": []}
我发现我可以用
检查一个词是否是回文
word.lower() == word.lower()[::-1]
我还可以用
将字符串拆分成单词
string.split()
但我不明白如何遍历字符串并构建字典,以便只有回文是键并同时制作列表。
感谢您的帮助
此代码应该有效:
text = "Bob and Anna are meeting at noon"
words = {}
last_p = None
for word in text.split():
word2 = word.lower()
if word2 == word2[::-1]:
words[word] = []
last_p = word
elif last_p:
words[last_p].append(word)
print(words)
如果第一个回文之前的句子中有任何单词,它们将被忽略。如果您希望字典中的项目保持原来的顺序,请使用 collections.OrderedDict
class 而不是内置的 dict
.
def is_palindrome(word):
return word.lower() == word.lower()[::-1]
def task(string):
words = string.split(' ')
returned = dict()
i = 0
while i < len(words):
if is_palindrome(words[i]): # if palindrome
returned[words[i]] = []
j = i + 1
while j < len(words) and not is_palindrome(words[j]):
returned[words[i]].append(words[j])
j += 1
i += 1
return returned
print(task("Bob and Anna are meeting at noon"))
尝试了解它的工作原理,这是您有时需要自己弄清楚的事情之一。
另外值得一提的是,字典没有排序,因此最终结果的成对排列可能会有所不同。
from collections import OrderedDict
s = "Bob and Anna are meeting at noon"
d = OrderedDict()
lastKey = None
for i in s.split():
if i.upper() == i.upper()[::-1]:
d[i] = []
lastKey = i
else:
if lastKey: d[lastKey].append(i)
print d
很抱歉,如果这太简单了,但我不知道如何构建这本词典。
例如我有一个字符串
"Bob and Anna are meeting at noon"
我想要一个字典,其中所有回文都指向以下非回文的列表,所以
{"Bob": ["and"], "Anna": ["are", "meeting", "at"], "noon": []}
我发现我可以用
检查一个词是否是回文word.lower() == word.lower()[::-1]
我还可以用
将字符串拆分成单词string.split()
但我不明白如何遍历字符串并构建字典,以便只有回文是键并同时制作列表。
感谢您的帮助
此代码应该有效:
text = "Bob and Anna are meeting at noon"
words = {}
last_p = None
for word in text.split():
word2 = word.lower()
if word2 == word2[::-1]:
words[word] = []
last_p = word
elif last_p:
words[last_p].append(word)
print(words)
如果第一个回文之前的句子中有任何单词,它们将被忽略。如果您希望字典中的项目保持原来的顺序,请使用 collections.OrderedDict
class 而不是内置的 dict
.
def is_palindrome(word):
return word.lower() == word.lower()[::-1]
def task(string):
words = string.split(' ')
returned = dict()
i = 0
while i < len(words):
if is_palindrome(words[i]): # if palindrome
returned[words[i]] = []
j = i + 1
while j < len(words) and not is_palindrome(words[j]):
returned[words[i]].append(words[j])
j += 1
i += 1
return returned
print(task("Bob and Anna are meeting at noon"))
尝试了解它的工作原理,这是您有时需要自己弄清楚的事情之一。
另外值得一提的是,字典没有排序,因此最终结果的成对排列可能会有所不同。
from collections import OrderedDict
s = "Bob and Anna are meeting at noon"
d = OrderedDict()
lastKey = None
for i in s.split():
if i.upper() == i.upper()[::-1]:
d[i] = []
lastKey = i
else:
if lastKey: d[lastKey].append(i)
print d