我需要从嵌套列表中获取配置文件,其中一个函数接受一个输入并添加或删除遵循规则的列表:
alex = ["python","java","c++"]
silvia = ["node","php","ruby"]
kevin = ["c++","js","css"]
people = [alex,silvia,kevin]
container = []
def _params(l,r):
"""l = list r = rule[str] """
string = r #this is for save input("programmer for:") not used yet
range1 = range(0,len(l))
for caracter in range1:
for x in l[caracter]:
if x == r: #this is var string for imput and _params(l) not used yet
container.append(l[caracter])
else:
people.remove(l[caracter])
return "success"
_params(people,"python")
print(container)
print(people)
列表应该是这样的:
people = [alex]
container = [alex]
它有效,但如果我改变:
_params(people,"node")
跳转到提示:
Traceback(最近一次调用最后一次): 文件“./rules”,第58行,in _params(人, “节点”) 在_params中输入“./rules”,第46行 for x in l [caracter]: IndexError:列表索引超出范围
也许我错过了一个明显的逻辑,我不是试图你们调试我的代码只是尝试理解我的整体逻辑是否错误。
编辑:
它以这种方式正常工作:
def _params(lts):
r = input("")
for i in range(len(lts)):
for i2 in range(len(lts[i])):
if r in lts[i]:
container.append(lts[i])
return none
print("choose option")
_params(people)
你的代码似乎过于复杂。如果container
最后等于people
,为什么要单独计算?
This is one way you can structure your code:
alex = ['python', 'java', 'c++']
silvia = ['node', 'php', 'ruby']
kevin = ['c++', 'js', 'css']
people = [alex, silvia, kevin]
container = []
def _params(lst, r):
for i in range(len(lst)):
if r in lst[i]:
container.append(lst[i])
return None
_params(people, 'node')
print(container)
# [['node', 'php', 'ruby']]
_params(people, 'python')
print(container)
# [['python', 'java', 'c++']]