Python creates multiple lists in loop
In Python, we can use list comprehensions or loops combined with conditional statements to create multiple lists. Here are some common scenarios and corresponding code examples:
1. Create a fixed number of empty lists
Suppose we need to create multiple empty lists, which can be used to comprehensions and loops:
# Create multiple empty lists using list comprehensionnum_lists = 5 empty_lists = [[] for _ in range(num_lists)] print(empty_lists)
This will create a list with 5 empty lists.
2. Create multiple lists based on conditions
Sometimes, we need to create different lists based on specific conditions. For example, we want to store odd and even numbers in two lists respectively:
# Create odd and even listsnumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] odd_numbers = [] even_numbers = [] for num in numbers: if num % 2 == 0: even_numbers.append(num) else: odd_numbers.append(num) print("Odd List:", odd_numbers) print("Even list:", even_numbers)
This creates two lists based on the parity of the numbers.
3. Create multiple lists based on string length
Sometimes, we need to classify and store strings in different lists according to their length:
# Create multiple lists based on string lengthwords = ["apple", "banana", "orange", "pear", "grape", "kiwi"] short_words = [] medium_words = [] long_words = [] for word in words: if len(word) < 5: short_words.append(word) elif len(word) < 7: medium_words.append(word) else: long_words.append(word) print("Short Word List:", short_words) print("Medium-length word list:", medium_words) print("Long Word List:", long_words)
This will store words in three different lists according to the length of the string.
4. Create multiple lists based on data type
Sometimes we need to store it in different lists based on the type of data. For example, we want to store integers, floating-point numbers, and strings in different lists:
# Create multiple lists based on data typedata = [1, 2.5, "apple", 4, "banana", 6.7, "orange", 8, 9, "pear"] integers = [] floats = [] strings = [] for item in data: if isinstance(item, int): (item) elif isinstance(item, float): (item) elif isinstance(item, str): (item) print("Integer List:", integers) print("Floating point number list:", floats) print("Standlist:", strings)
This will store it in three different lists based on the type of data.
5. Dynamically create multiple lists based on conditions
Sometimes, we need to create multiple lists based on dynamically changing conditions. For example, we want to create a list of corresponding quantities based on the number entered by the user:
# Dynamically create multiple lists based on user inputnum_lists = int(input("Please enter the number of lists to create: ")) lists = [[] for _ in range(num_lists)] print("Created", num_lists, "Empty list:", lists)
This will dynamically create a corresponding number of empty lists based on the number entered by the user.
6. Create multiple lists of numbers with specific ranges
Sometimes, we need to create multiple lists based on numbers in a specific range. For example, we want to store numbers between 0 and 9 in a single digit in a list of ten:
# Create multiple lists of numbers with specific rangesnum_lists = 10 range_lists = [[] for _ in range(num_lists)] for num in range(10): range_lists[num % num_lists].append(num) print("Stored list by single digits:") for i, lst in enumerate(range_lists): print(f"List{i}:", lst)
This will store numbers between 0 and 9 in the ten lists in single digits.
7. Create multiple lists based on the hash of the key
Sometimes, we want to group data in multiple lists based on the hash value of the key. For example, we have a set of key-value pairs that we want to store in a different list based on the hash of the key:
# Create multiple lists based on the hash of the keydata = {"apple": 3, "banana": 5, "orange": 2, "pear": 4, "grape": 6} num_lists = 3 hash_lists = [[] for _ in range(num_lists)] for key, value in (): hash_index = hash(key) % num_lists hash_lists[hash_index].append((key, value)) print("List stored according to the hash value of the key:") for i, lst in enumerate(hash_lists): print(f"List{i}:", lst)
This will store key-value pairs in three different lists based on the hash value of the key.
8. Create multiple lists based on attributes of elements in the list
Sometimes, we need to create multiple lists based on the attribute values of elements in the list. For example, suppose we have a group of student objects and we want to store them in two lists of passing and failing according to their grades:
# Create multiple lists based on student subject's gradesclass Student: def __init__(self, name, score): = name = score students = [ Student("Alice", 85), Student("Bob", 60), Student("Charlie", 75), Student("David", 40), Student("Emma", 95) ] passing_students = [] failing_students = [] for student in students: if >= 60: passing_students.append(student) else: failing_students.append(student) print("Current Student List:") for student in passing_students: print(f"{}: {}") print("\nFailed Student List:") for student in failing_students: print(f"{}: {}")
This will store students in two lists of passing and failing, based on the grades of the student subject.
9. Create multiple lists based on index range
Sometimes, we need to split the list into multiple sublists based on the index range. For example, we have a list of numbers that we want to split into several small sublists:
# Create multiple lists based on index rangenumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] num_lists = 3 split_lists = [] for i in range(num_lists): start_index = i * len(numbers) // num_lists end_index = (i + 1) * len(numbers) // num_lists split_lists.append(numbers[start_index:end_index]) print("Segmented List:") for i, lst in enumerate(split_lists): print(f"List{i + 1}:", lst)
This will split the original list into three sublists based on the index range.
10. Create multiple lists based on the value of the list element
Sometimes we need to group the values of list elements and store them in different lists. For example, suppose we have a set of integers and we want to store them in two lists according to their parity:
# Create multiple lists based on the value of the list elementnumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] odd_numbers = [] even_numbers = [] for num in numbers: if num % 2 == 0: even_numbers.append(num) else: odd_numbers.append(num) print("Odd List:", odd_numbers) print("Even list:", even_numbers)
This will store the list elements in the odd and even lists, respectively.
11. Create multiple lists based on whether the element meets the criteria
Sometimes, we need to store elements in different lists based on whether they meet certain conditions. For example, suppose we have a set of numbers, and we want to store numbers greater than or equal to 5 and less than 5 in two lists, respectively:
# Create multiple lists based on whether the element meets the criterianumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] greater_than_5 = [] less_than_5 = [] for num in numbers: if num >= 5: greater_than_5.append(num) else: less_than_5.append(num) print("List of numbers greater than or equal to 5:", greater_than_5) print("List of numbers less than 5:", less_than_5)
This will store the number in two different lists based on whether it is greater than or equal to 5.
Summarize
In general, this article introduces multiple methods of creating multiple lists using loops in Python, and is demonstrated and explained through specific code examples. From different perspectives such as fixed quantity, conditions, data type, attributes, index range, hash value, etc., we explore how to flexibly use loop combination list comprehension or conditional statements to create multiple lists. These methods not only improve code flexibility and maintainability, but also speed up the development process and improve program performance.
Through the study of this article, readers can master the skills of processing data in Python and organizing it into multiple lists, thereby more efficiently performing data manipulation and management. At the same time, the flexibly using Python features such as loops and list comprehensions can make the code more concise, clear and elegant. In actual projects, selecting the right method to create multiple lists based on specific needs will become an important skill in programming, helping to improve the quality and efficiency of the code.
The above is the detailed content shared by 11 Python loop techniques. For more information about Python loops, please follow my other related articles!