Python列表高效拆分:快速拆分元素及64位元素转十六进制列表
1. Fast Method to Split Each Element of a List into a New List
Depending on what you mean by "split each element", here are two common scenarios with efficient, Pythonic solutions:
Scenario 1: Splitting String Elements by a Delimiter
If your original list has strings that need to be split into sub-elements (like comma-separated values), list comprehensions are the way to go—they’re optimized for speed and keep your code concise.
Example Input:
original_list = ["apple,banana,cherry", "date,fig,grape"]
Expected Output:
["apple", "banana", "cherry", "date", "fig", "grape"]
Code:
split_list = [item for s in original_list for item in s.split(',')]
Scenario 2: Flattening Nested Lists/Iterables
If each element in your list is an iterable (sublist, tuple, set, etc.) and you want to flatten everything into a single list, a list comprehension is still the fastest approach.
Example Input:
nested_list = [[1, 2, 3], (4, 5), {6, 7}]
Expected Output:
[1, 2, 3, 4, 5, 6, 7]
Code:
flattened_list = [item for sub_iter in nested_list for item in sub_iter]
For large datasets, list comprehensions outperform manual for loops with append() calls because they run in optimized C code under the hood.
2. Splitting 64-bit Elements into Individual Hex Characters
Let’s break down the input format, expected output, and solution clearly:
Input Format
A list of 64-bit integers (or pre-formatted 16-character hex strings—since 64 bits equal exactly 16 hex digits). For integers, they should fall within the range 0 to 0xFFFFFFFFFFFFFFFF (inclusive).
Example Input:
# 64-bit integers bit64_list = [0x1A2B3C4D5E6F7890, 0x00FF11EE22DD33CC] # Or equivalent 16-character hex strings bit64_str_list = ["1A2B3C4D5E6F7890", "00FF11EE22DD33CC"]
Expected Output
A list where each element is a sublist containing individual hexadecimal characters (uppercase or lowercase, your choice). Each sublist will have exactly 16 elements (one per hex digit).
Example Output:
[ ['1', 'A', '2', 'B', '3', 'C', '4', 'D', '5', 'E', '6', 'F', '7', '8', '9', '0'], ['0', '0', 'F', 'F', '1', '1', 'E', 'E', '2', '2', 'D', 'D', '3', '3', 'C', 'C'] ]
Solution Code
For 64-bit Integers
First convert each integer to a 16-character hex string (adding leading zeros to ensure full 64-bit representation), then split it into individual characters:
# For uppercase hex characters hex_char_lists = [list(f"{x:016X}") for x in bit64_list] # For lowercase hex characters, use: # hex_char_lists = [list(f"{x:016x}") for x in bit64_list]
For Pre-formatted Hex Strings
If your input is already 16-character hex strings, simply convert each string to a list of characters:
hex_char_lists = [list(s) for s in bit64_str_list]
This method is efficient and guarantees you get exactly the 16 hex characters per 64-bit element.
内容的提问来源于stack exchange,提问作者Eduardo Andrade

