Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将新子列表添加到现有列表_Python_List_Sublist - Fatal编程技术网

Python 将新子列表添加到现有列表

Python 将新子列表添加到现有列表,python,list,sublist,Python,List,Sublist,各位! 我试图在现有列表中添加一个新的子列表,但我不太确定如何添加。这是我的密码: data = [[4,5],[3,7]] search = 9 for sublist in data: if search in sublist: sublist.append(0) print("there", sublist) break else: print("not there") break

各位!

我试图在现有列表中添加一个新的子列表,但我不太确定如何添加。这是我的密码:

data = [[4,5],[3,7]]
search = 9
for sublist in data:
    if search in sublist:
        sublist.append(0)
        print("there", sublist)
        break
    else:
        print("not there")
        break
        def sublist():
            [5,6]
            print[data]
但是,如果不存在搜索,则子列表不会添加到原始列表中。我该怎么做

干杯! 5813

只需附加它:

>>> data = [[4,5],[3,7]]
>>> data.append([5,6])
>>> data
[[4, 5], [3, 7], [5, 6]]

您应该缩进
else
块。for/else是完全不同的(尽管在这种情况下它可以工作)

如果搜索不在子列表中,则将子列表(我认为您希望将
[5,6]
添加到主列表)附加到
数据中:

for sublist in data:
    if search in sublist:
        sublist.append(0)
        print("there", sublist)
        break
    else:
        print("not there")
        data.append([5, 6])

如果您确实打算使用for/else循环,那么只需在
else
之后执行
data.append([5,6])
。我不知道您希望函数定义做什么(它坐在那里什么也做不了)。

简单

data= [[1, 2], [3, 4], [5, 6]]
for sublist in data:
    sublist.append("a")

“你期望那行代码做什么?”瓦利德汗澄清道