【问题标题】:Remove and append from nested list从嵌套列表中删除和追加
【发布时间】:2018-02-18 17:35:53
【问题描述】:

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

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

跳转到提示:

回溯(最近一次通话最后一次):
文件“./rules”,第 58 行,在
_params(人,“节点”)
文件“./rules”,第 46 行,在 _params
对于 l[caracter] 中的 x:
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)

【问题讨论】:

  • if x == y: 中的y 是什么?这似乎没有在您提供的代码中的任何地方定义。
  • caracter = 在 l 索引上的迭代 x = carater 索引的迭代 y = r 这是一个打字错误,但在代码中是 r 我想说的是搜索人,而在这个人中搜索某人谁知道python,把这个人加到“容器”中,在“人”中删除所有不知道python的人。
  • 那为什么没有在你的代码中定义呢?您可以更新您的代码以使其完整吗?
  • 完成了,这就是目前完整的固定代码。

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多