从嵌套列表

时间:2018-02-18 17:35:53

标签: python python-3.x list nested-lists

我需要从嵌套列表中获取配置文件,其中包含一个输入并添加或删除遵循规则的列表的功能:

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")

跳到promt:

  

追踪(最近的呼叫最后):
    文件“./rules”,第58行,在       _params(人, “节点”)
    文件“./rules”,第46行,在_params中       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)

1 个答案:

答案 0 :(得分:0)

您的代码似乎过于复杂。如果最后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++']]