我想从函数返回的索引中创建大写的2d列表元素。例如:
crosswords=[['s','d','o','g'],['c','u','c','m'],['a','x','a','t'],['t','e','t','k']]
word='cat',
然后我的函数应该返回:
[['s','d','o','g'],['C','u','c','m'],['A','x','a','t'],['T','e','t','k']]
以下是我的尝试:
def find_word_vertical(crosswords, word):
x=zip(*crosswords)
#print x
for row in x:
join_list = "".join(row)
if join_list.find(word) != -1:
return [row.index(word[0]),x.index(row)]
break
def find_word_horizontal(crosswords, word):
for row in crosswords:
join_list = "".join(row)
if join_list.find(word) != -1:
return [crosswords.index(row), row.index(word[0])]
break
def capitalize_word_in_crossword(crosswords,word):
if find_word_horizontal or find_word_vertical is not None:
for i in word:
for j in crosswords:
if i in j:
i.upper()
return crosswords
以下是结果:
[['s', 'd', 'o', 'g'], ['c', 'u', 'c', 'm'], ['a', 'c', 'a', 't'], ['t', 'e', 't', 'k']]
任何人都可以帮助我吗?
答案 0 :(得分:1)
您可以使用列表推导找到水平和垂直事件。
横向出现的是:
LD_LIBRARY_PATH
垂直事件是:
>>> filter(
lambda (_, j): j > -1,
[(i, ''.join(w).find(word)) for i, w in enumerate(crosswords)])
[]
通过这些事件,可以轻松选择如何处理它们(选择on或all,更喜欢水平到垂直等),包括大写它们。