Python实现循环获取元素前后值的优化方法咨询
Great question! Your current dummy function works perfectly, but we can make it more elegant, scalable, and concise using modular arithmetic—which is ideal for circular sequences since it handles wrap-around logic automatically without clunky conditional checks.
Approach 1: Modular Arithmetic (Best for Consecutive Sequences)
Since your sequence is a consecutive 1-based circular list of 6 elements, modulo operations let us compute previous and next values in one line each. Here's the refined function:
def getPrevNext(no): TOTAL_ELEMENTS = 6 prev_no = (no - 2) % TOTAL_ELEMENTS + 1 next_no = no % TOTAL_ELEMENTS + 1 return [prev_no, next_no]
How this works:
- Previous element: Subtract 2 to shift back by one and adjust for 1-based indexing, take modulo 6 to wrap around from 1 to 6, then add 1 to return to 1-based numbering.
- For
no=1:(1-2) % 6 = 5 → 5+1=6(correct) - For
no=6:(6-2) %6=4 →4+1=5(correct)
- For
- Next element: Take modulo 6 (so 6 becomes 0), then add 1 to wrap around to 1.
- For
no=6:6%6=0 →0+1=1(correct) - For
no=5:5%6=5 →5+1=6(note: your example had a typo here—your originaldummyfunction returns 6 forno=5, which is the correct next element)
- For
This approach shines because:
- It’s scalable: Just update
TOTAL_ELEMENTSif your sequence length changes (no need to rewrite conditionals) - No messy branches: Clean, one-line calculations replace the
if/elif/elseblock - Easy to maintain: The logic stays consistent even as the sequence grows
Approach 2: Dictionary Lookup (Useful for Non-Consecutive Sequences)
If your sequence ever becomes non-consecutive (e.g., [1,3,5,7,9,11]), a dictionary lookup is a clean alternative:
def getPrevNext(no): sequence_map = { 1: (6, 2), 2: (1, 3), 3: (2, 4), 4: (3, 5), 5: (4, 6), 6: (5, 1) } return list(sequence_map[no])
This is O(1) time, but less scalable for long sequences—you’d have to manually update the dictionary. For your current consecutive sequence, the modular approach is far better.
Testing the Function
Let’s verify with your examples (correcting the typo for no=5):
print(getPrevNext(2)) # [1, 3] ✔️ print(getPrevNext(5)) # [4, 6] ✔️ print(getPrevNext(1)) # [6, 2] ✔️ print(getPrevNext(6)) # [5, 1] ✔️
All cases work as expected!
内容的提问来源于stack exchange,提问作者Shubham R

