목록 파이썬

목록은 대괄호 안에 구성되는 Python의 변경 가능한 데이터 유형입니다. 이 문서는 예제가 포함된 Python 목록 목록에 관한 것입니다.
Python의 목록 목록은 목록의 각 요소 자체가 목록임을 의미합니다. 목록에는 목록이 요소로 포함되어 있습니다.

내용의 테이블


  • How to create a list of lists in Python?
  • How to make a list of lists from a single list in Python?
  • How to generate a list of lists
  • How to convert multiple lists into a list of lists
  • How to convert the list of lists into a NumPy array
  • How to convert into a list of lists to string in python
  • How to convert into a list of lists to set in python
  • How to convert set to list of lists in python
  • How to convert a list of lists to a List of tuples in python
  • How to Convert List of Tuples to List of Lists in Python?
  • How to convert a list of lists to Dataframe in python
  • How to convert DataFrame to a list of lists
  • How to convert a list of lists to Dictionary in python
  • How to convert a dictionary to a list of lists in python
  • Sort a List of Lists in Python
  • Sort a list of lists in ascending order
  • Sort a list of lists in descending order
  • Sort a list of lists by length
  • Operations of a list of lists
  • Python Zip List of Lists
  • Python Unpack List of Lists
  • Transpose list of lists in Python
  • Append list of lists in python
  • Item inside sub list of a list
  • Insert a list inside a list
  • Extend python list of lists
  • Pop list of lists
  • Concatenation list of lists in python
  • Remove the duplicate item from the list of lists
  • Print list of lists without brackets
  • Call the list of lists by using the index number
  • Access to the item of the list of lists in python
  • Delete the list of lists in python
  • Conclusion

  • Python에서 목록 목록을 만드는 방법은 무엇입니까?

    To Enclose multiple lists as an item inside square brackets.
    Suppose to create a nested list to add all lists as elements inside a list.
    a = [1,2,3],b = [3,4,5],c = [6,7,8] => list_of_list [[1,2,3], [3,4,5], [6,7,8]]

    Python의 단일 목록에서 목록 목록을 만드는 방법은 무엇입니까?

    Use the abstract syntax Trees to convert the single list into a list of lists in python (Nested List)

    import ast
    
    # List Initialization
    list1 = ['1 , 2',  '7 , 9',  '34 , 98', '66 , 89347', '723, 54, 0']
    # using ast to convert
    ListOfLists = [list(ast.literal_eval(x)) for x in list1]
    # printing
    print(ListOfLists)
    

    Output

    [[1, 2], [7, 9], [34, 98], [66, 89347], [723, 54, 0]]
    

    목록 목록을 생성하는 방법

    ● Define blank list
    ● Define the range of the list of lists (item) from 0 to 3
    ● Create a sub-list inside every nested list of range from 1 to 5
    ● Print

    listoflists = []
    for i in range(0,3):
        sublist = []
        for j in range(1,5):
             sublist.append((i,j))
        listoflists.append(sublist)
    print (listoflists)
    

    Output

    [[(0, 1), (0, 2), (0, 3), (0, 4)], [(1, 1), (1, 2), (1, 3), (1, 4)], [(2, 1), (2, 2), (2, 3), (2, 4)]]
    
    

    여러 목록을 목록 목록으로 변환하는 방법

    Call the multiple lists inside the square brackets with lists name that will embed the multiple lists into a lists

    list1=[1,2]
    list2=[3,4]
    list3=[4,5,6]
    
    print("List 1:" +str(list1))
    print("List 2:" +str(list2))
    print("List 3:" +str(list3))
    
    listoflists=[list1, list2, list3]
    print ("List of lists"+str(listoflists))
    

    Output

    List 1:[1, 2]
    List 2:[3, 4]
    List 3:[4, 5, 6]
    List of lists[[1, 2], [3, 4], [4, 5, 6]]
    

    목록 목록을 NumPy 배열로 변환하는 방법

    Import NumPy library that converts a list of lists into a 2-Dimensional array in Python.

    # Import the NumPy library
    import numpy as nmp
    # Create the list of lists
    list_of_lists = [['x', 'y', 'z'], [4, 5, 6], [7, 8, 9]]
    # Convert it to an array
    arr = nmp.array(list_of_lists)
    # Print as array
    print(arr)
    
    

    output

    [['x' 'y' 'z']
     ['4' '5' '6']
     ['7' '8' '9']]
    

    파이썬에서 목록 목록을 문자열로 변환하는 방법

    ● Define the lists of characters in a list
    ● Use the join method that connects each character of a defined list
    ● Map the two lists as two words

    # Convert List of lists to Strings
    
    a= [["M", "y"],["C", "o", "d", "e"]]
    res = list(map(''.join, a))
    print(*res, sep=" ")
    

    output

    My Code
    

    파이썬에서 설정할 목록 목록으로 변환하는 방법

    ● Use the map method with a set function that removes duplicate items from the list.
    ● print list of lists as set in python.

    # Convert List of lists to Set
    
    a= [[1,2,3,4],["a", "a", "b", "e"],["Sam", "John"]]
    res = list(map(set,a))
    print(*res, sep=" ")
    
    

    Output

    {1, 2, 3, 4} {'b', 'a', 'e'} {'Sam', 'John'}
    

    Python에서 목록 목록으로 설정을 변환하는 방법

    ● Use the comprehension method that iterates each object of the set sequentially
    ● Use “list” to convert a defined set into a list
    ● n defined the number of nested lists.
    ● Print a Python list of lists with the help of the comprehension method.

    my_set = set({1, 4, 2, 3, 5, 6, 7, 8,})
    l = list(my_set)
    n = 3   
    # using list comprehension 
    x = [l[i:i + n] for i in range(0, len(l), n)] 
    print(x)
    

    Output

    [[1, 2, 3], [4, 5, 6], [7, 8]]
    

    파이썬에서 목록 목록을 튜플 목록으로 변환하는 방법

    Tuples stores data in an ordered form.
    ● Use map function with built-in tuple method to convert the list of lists into tuple in python.

    a= [[1,2,3,4],["a", "a", "b", "e"],["Sam", "John", "Morgan"]]
    tuples = list(map(tuple, a))
    print(tuples)
    

    output

    [(1, 2, 3, 4), ('a', 'a', 'b', 'e'), ('Sam', 'John', 'Morgan')]
    

    Python에서 튜플 목록을 목록 목록으로 변환하는 방법은 무엇입니까?

    Perform the reverse operation to convert tuples into the list of lists.
    ● Use the built-in list function to convert a list of tuples into a list of lists.
    ● For loop iterate each element of tuple and print as a nested list.

    tuples = [(1, 2, 3), (4, 5, 6), (90, 376, 84)]
    lists = [list(a) for a in tuples]
    print(lists)
    

    output

    [[1, 2, 3], [4, 5, 6], [90, 376, 84]]
    

    Python에서 목록 목록을 Dataframe으로 변환하는 방법

    DataFrame is a labeled data structure that is 2-Dimensional. It contains columns and rows that may contain different data types inside it.
    ● Import Pandas library to convert a list of lists to dataframe.
    ● Define a list of lists.
    ● Define columns name with the same length of list items. E.g., 3 columns name for 3 data inside the nested list
    ● Print as a column labeled data with index number automatically.

    import pandas as pd
    data = [['DSA', 'Python', 80],
              ['DS', 'MATLAB', 70],
              ['OSDC', 'C', 94],
              ['MAPD', 'JAVA', 78]]
    df = pd.DataFrame(data, columns=['Subject', 'Language', 'Marks'])
    print(df)
    

    Output

    Subject Language  Marks
    0     DSA   Python     80
    1      DS   MATLAB     70
    2    OSDC        C     94
    3    MAPD     JAVA     78
    

    DataFrame을 목록 목록으로 변환하는 방법

    Perform the reverse function to convert the dataframe into the list of lists by using a built-in list function .

    import pandas as pd
    df = pd.DataFrame(
              [['DSA', 'Python', 80],
              ['DS', 'MATLAB', 70],
              ['OSDC', 'C', 94],
              ['MAPD', 'JAVA', 78]], columns= ['Subject', 'Language', 'Marks'])
    print ("DataFrame Output")
    print(df)
    
    def dfToTable(df:pd.DataFrame) -> list:
     return [list(df.columns)] + df.values.tolist()
    
    print("\n Convert DataFrame to  list of lists :" +str(dfToTable(df)))
    

    output

    DataFrame Output
      Subject Language  Marks
    0     DSA   Python     80
    1      DS   MATLAB     70
    2    OSDC        C     94
    3    MAPD     JAVA     78
    
     Convert DataFrame to  list of lists :[['Subject', 'Language', 'Marks'], ['DSA', 'Python', 80], ['DS', 'MATLAB', 70], ['OSDC', 'C', 94], ['MAPD', 'JAVA', 78]]
    

    Python에서 목록 목록을 사전으로 변환하는 방법

    Dictionary contains keys with their values in ordered form without duplication.
    ● Define a list of lists
    ● Use for loop to iterate key with index 0 and value with index 1 and print as a dictionary

    a = [['samsung', 1],['OPPO', 3],['iPhone', 2], ['Huawei', 4]]
    data_dict = {}
    for x in a:
       data_dict[x[0]] = x[1]
    print(data_dict)
    

    Output

    {'samsung': 1, 'OPPO': 3, 'iPhone': 2, 'Huawei': 4}
    

    파이썬에서 사전을 목록 목록으로 변환하는 방법

    ● Define the dictionary with key and their values.
    ● Convert to list of lists with map and list function

    dict = {'samsung': 1, 'OPPO': 3, 'iPhone': 2, 'Huawei': 4}
    a= list(map(list, dict.items()))
    print(a)
    

    Output

    [['samsung', 1], ['OPPO', 3], ['iPhone', 2], ['Huawei', 4]]
    

    Python에서 목록 목록 정렬

    오름차순으로 목록 목록 정렬

    Sort according to the first element of each nested list. It sorts the list according to the first value of each nested list. This method makes changes to the original list itself.

    A = [[5, 90], [4, 89], [2, 70], [1, 0]]
    print("Orignal List:" +str(A))
    A.sort()
    print("New sorted list A is: % s" % (A))
    

    *Output *

    Orignal List:[[5, 90], [4, 89], [2, 70], [1, 0]]
    New sorted list A is: [[1, 0], [2, 70], [4, 89], [5, 90]]
    

    목록 목록을 내림차순으로 정렬

    Use reverse sorting order to sort a list of lists in descending manner.

    A = [[5, 90], [4, 89], [2, 70], [1, 0]]
    print("Orignal List:" +str(A))
    A.sort(reverse=True)
    print("Descending/reverse sorted list A is: % s" % (A))
    

    *Output *

    Orignal List:[[5, 90], [4, 89], [2, 70], [1, 0]]
    Descending/reverse sorted list A is: [[5, 90], [4, 89], [2, 70], [1, 0]]
    

    목록 목록을 길이별로 정렬

    Sort a list of lists according to the length of each list. “len” function sorts the list with the long length first.

    A = [[1, 2, 3, 4],['a', 'b', 'c', 'd'],[1, 5, 6, 'f', 'a']]
    A.sort(key=len)
    print(A)
    

    output

    [[1, 2, 3, 4], ['a', 'b', 'c', 'd'], [1, 5, 6, 'f', 'a']]
    

    목록 목록의 작업

    목록의 Python Zip 목록

    Define three lists and zipped them into a list of lists with the help of the zip method

    Domain = ['Software', 'Networking', 'Telecommunication']
    Students = [8345, 8437, 422]
    Companies = ['Microsoft', 'CISCO', 'AT&T']
    
    zipped = zip(Domain, Students, Companies)
    print(list(zipped))
    

    Output

    [('Software', 8345, 'Microsoft'), ('Networking', 8437, 'CISCO'), ('Telecommunication', 422, 'AT&T')]
    

    Python 목록 목록 풀기

    Use for loop with map and join function to unpack the zipped list of lists.

    members= [('Software', 8345, 'Microsoft'), ('Networking', 8437, 'CISCO'), ('Telecommunication', 422, 'AT&T')]
    for item in members:
        print (' '.join(map(str, item)))
    

    *Output *

    Software 8345 Microsoft
    Networking 8437 CISCO
    Telecommunication 422 AT&T
    In [ ]:
    

    Python의 목록 목록 바꾸기

    This method transposes the array to a list with the help of the NumPy library. This method changes the fashion of the array by taking 1st element of each list into 1st list, 2nd element of each array into the 2nd list, and 3rd element of each array into 3rd list in the output.

    import numpy as np
    l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    b= np.array(l).T.tolist()
    print(b)
    

    Output

    [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
    

    파이썬에서 목록 목록 추가

    Append is a built-in function of python programming that helps to append the additional sublist inside the list.

    list1 = [["apple"], ["banana", "grapes"],["cherry", "guava"]]
    AddList = [1, 2, 3]
    list1.append(AddList)
    print(list1)
    

    Output

    [['apple'], ['banana', 'grapes'], ['cherry', 'guava'], [1, 2, 3]]
    

    목록의 하위 목록 내부 항목

    To append the additional item inside the list of lists with the help of the index value. e.g., a[2].append(4): append 4 in list number 2. ( index starts from 0)

    a= [["apple"], ["banana", "grapes"] ,["cherry", "guava"]]
    a[2].append(4)
    print(a)
    

    Output

    [['apple'], ['banana', 'grapes'], ['cherry', 'guava', 4]]
    

    목록 안에 목록 삽입

    Insert take two arguments. insert (position, item)
    ● the position where the list add. e.g., 2
    ● The item that adds to the list

    a = [[1, 2], [3, 4],[5]]
    print(a)
    list1=[1, 2]
    a.insert(2,list1)
    print(a)
    

    Output

    [[1, 2], [3, 4], [5]]
    [[1, 2], [3, 4], [1, 2], [5]]
    

    목록의 파이썬 목록 확장

    Use extend function to extend the number of lists inside a list

    a = [['Samsung', 'Apple']]
    b = [[6, 0, 4, 1]]
    a.extend(b)
    print (a)
    

    Output

    [['Samsung', 'Apple'], [6, 0, 4, 1]]
    In [ ]:
    

    목록의 팝 목록

    The pop method removes the item defined item in the index
    ● Define 3 lists.
    ● Convert into a list of lists
    ● Remove item that is on the position of index 1 from that index number is 2
    Note: index number starting from 0

    list1=[1,2]
    list2=[3,4]
    list3=[4,5,6]
    listoflists=[list1, list2, list3]
    
    print ("Orignal List of lists:"+str(listoflists))
    listoflists[2].pop(1)
    print ("Popped list:" +str(listoflists))
    

    Output

    Orignal List of lists:[[1, 2], [3, 4], [4, 5, 6]]
    Popped list:[[1, 2], [3, 4], [4, 6]]
    

    파이썬에서 목록의 연결 목록

    Concatenate a list of lists to convert into a single list, using the sum operation.
    ● Define the list of lists
    ● Use sum property to concatenate the lists

    z = [["a","b"], ["c"], ["d", "e", "f"]]
    
    result = sum(z, [])
    print(result) 
    

    Output

    ['a', 'b', 'c', 'd', 'e', 'f']
    

    목록 목록에서 중복 항목 제거

    Except “set” property, there is another method that removes the duplicate item from the list of lists
    Use gruopby of itertools that will sort the list of lists one by one and remove duplicate nested lists from the list.

    import itertools
    a = [[5, 8], [4], [5], [5, 6, 2], [1, 2], [3], [4], [5], [3]]
    a.sort()
    l= list(k for k,_ in itertools.groupby(a))
    print(l)
    

    output

    [[1, 2], [3], [4], [5], [5, 6, 2], [5, 8]]
    

    대괄호 없이 목록 목록 인쇄

    This method converts and prints all the items of the list without square brackets and prints them as comma-separated values.

    a=[["Cricket", 2], ["Football",6,  5], ["Tennis", 2], ["Hockey", 2] ]
    for item in a:
        print(str(item[0:])[1:-1])
    

    output

    'Cricket', 2
    'Football', 6, 5
    'Tennis', 2
    'Hockey', 2
    In [ ]:
    

    인덱스 번호를 사용하여 목록 목록 호출

    To access the particular list inside the list, use the list position as an index when calling the print command.
    e.g. x [2]: item 3 of list x (index count start from 0)

    x = [["a","b"], ["c"], ["d", "e", "f"]]
    print(x[2])
    

    Output

    ['d', 'e', 'f']
    

    Python의 목록 목록 항목에 대한 액세스

    e.g. x [2][1]: element 2 of list 3 of list

    x = [["a","b"], ["c"], ["d", "e", "f"]]
    print(x[2][1])
    

    Output

    e
    

    파이썬에서 목록 목록 삭제

    Use del with position index that wants to delete and print a modified list of list.

    x = [["a","b"], ["c"], ["d", "e", "f"]]
    del x[1]
    print(x)
    

    Output

    [['a', 'b'], ['d', 'e', 'f']]
    
    

    결론

    In this article, we have tried to cover all the operations such as all types of Sorting of the list of lists, Conversion of the list of lists, deletion, insertion, extension, concatenation, append, etc.

    좋은 웹페이지 즐겨찾기