从嵌套lis中删除和附加

2024-03-29 15:29:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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:

Traceback (most recent call last):
File "./rules", line 58, in
_params(people,"node")
File "./rules", line 46, in _params
for x in l[caracter]:
IndexError: list index out of range

也许我遗漏了一个明显的逻辑,我不是想让你们调试我的代码,只要试着理解我的整体逻辑是否错误。你知道吗

编辑:

它可以这样正常工作:

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)

Tags: innode列表forlencontainerrangeparams
1条回答
网友
1楼 · 发布于 2024-03-29 15:29:08

你的代码似乎太复杂了。如果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++']]

相关问题 更多 >