[英]Accessing a repeated element in the list and printing the element next to it
我有这个函数,它有3个参数。 1)包含字符串的列表,2)search_term和3)place(可选参数)。
码:
def ls_src(list,search_term,place=1):
if search_term in list:
a = list[list.index(search_term)+1]+':' + '\tThe second element of of search term is ' + (search_term[place])
return a
现在我想访问search_term旁边的元素,但是如果元素在列表中重复,它还应该考虑该元素的其他实例,而不是仅仅元素的第一次出现。
如果list_search(['a','b','c','a','e'],'a')
那么,函数应该返回'b'和'e'两者,因为它们是下一个元素到'a'。
所以我的问题是,我们如何访问“a”的其他事件,而不仅仅是第一次出现。
您需要使用enumerate
函数,这有助于获取元素及其索引。
def list_search(l, s):
for i,j in enumerate(l):
if j == s:
print(l[i+1])
list_search(['a','b','c','a','e'],'a')
输出:
b
e
要么
搜索元素可能最后也存在,所以将print语句放在try
except
块except
。
def list_search(l, s):
for i,j in enumerate(l):
if j == s:
try:
print(l[i+1])
except IndexError:
pass
list_search(['a','b','c','a','e', 'a'],'a')
如果您更喜欢更具描述性的代码,您可以采取这样的方法。 它有点长,但你避免使用一个字符变量。
这提供的另一个方面是如果查询字符串跟随自身,则不会返回它。 这可以通过删除最后一个if
测试来改变。
def search_terms(terms, query):
found = []
count = len(terms)
for index, term in enumerate(terms):
next_index = index + 1
if term == query and next_index < count and terms[next_index] != query:
found.append(terms[next_index])
return found
print search_terms(['a', 'a', 'b', 'c', 'a', 'e', 'a'], 'a')
# ['b', 'e']
您可以使用迭代器和next()
函数构建新列表。
def list_search(input_list, search_term, place=1):
terms = iter(input_list)
new_list = []
try:
[new_list.append(terms.next()) for term in terms if term == search_term[place-1]]
except StopIteration:
pass
return new_list
tests = [
(['a','b','c','a','e'], 'a', 1),
(['a','b','c','a','e'], 'b', 1),
(['a','b','c','a','e'], 'ab', 2),
(['a','b','c','a','e'], 'e', 1),
(['a','a','a'], 'b', 1),
(['a','a','a'], 'a', 1)]
for input_list, search_term, place in tests:
print list_search(input_list, search_term, place)
这些测试将为您提供以下结果:
['b', 'e']
['c']
['c']
[]
[]
['a']
码:
def search(l,term):
for num in range(len(l)):
if l[num]==term:
print (l[num+1])
搜索(['python','html','python','c ++','python','java'],'python')
输出:
html
c++
java
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.