📜  在Python中打乱元组的方法

📅  最后修改于: 2022-05-13 01:55:44.302000             🧑  作者: Mango

在Python中打乱元组的方法

在编程实践中,洗牌有时可以证明是一个很大的帮助。这个过程可以直接在像列表一样可变的数据结构上实现,但是我们知道元组是不可变的,所以不能直接洗牌。如果您尝试按照以下代码中的方式进行操作,则会引发错误。让我们看看下面的例子。

Python3
import random
  
# Initializing tuple
t = (1,2,3,4,5)
  
# Trying to shuffle using random.shuffle
random.shuffle(t)


Python3
# Python3 code to demonstrate  
# shuffle a tuple  
# using random.shuffle() 
import random 
  
# initializing tuple
tup = (1,2,3,4,5)
  
# Printing original tuple
print("The original tuple is : " + str(tup))
  
# Conversion to list
l = list(tup)
  
# using random.shuffle() 
# to shuffle a list
random.shuffle(l)
  
# Converting back to tuple
tup = tuple(l)
  
# Printing shuffled tuple
print ("The shuffled tuple is : " + str(tup))


Python3
# Python3 code to demonstrate  
# shuffle a tuple  
# using random.sample() 
import random 
  
# initializing tuple
tup = (1,2,3,4,5)
  
# Printing original tuple
print("The original tuple is : " + str(tup))
  
# Using random.sample(), passing the tuple and 
# the length of the datastructure as arguments
# and converting it back to tuple.
tup = tuple(random.sample(t, len(t)))
  
# Printing shuffled tuple
print ("The shuffled tuple is : " + str(tup))


输出:

TypeError: 'tuple' object does not support item assignment

那么如何进行呢?所以有两种方法可以洗牌元组,下面会提到它们:

方法#1:类型转换

这是一种在元组中进行改组的简单方法。您可以将元组类型转换为列表,然后对列表执行洗牌操作,然后将该列表类型转换回元组。一种方法是使用 random.shuffle()。

Python3

# Python3 code to demonstrate  
# shuffle a tuple  
# using random.shuffle() 
import random 
  
# initializing tuple
tup = (1,2,3,4,5)
  
# Printing original tuple
print("The original tuple is : " + str(tup))
  
# Conversion to list
l = list(tup)
  
# using random.shuffle() 
# to shuffle a list
random.shuffle(l)
  
# Converting back to tuple
tup = tuple(l)
  
# Printing shuffled tuple
print ("The shuffled tuple is : " + str(tup))

输出:

The original tuple is: (1, 2, 3, 4, 5)
The shuffled tuple is: (2, 3, 4, 1, 5)

方法 #2:使用random.sample()

random.sample() 创建一个新对象,即使元组作为第一个参数传递,它也会返回一个列表,因此作为最后一步,必须将列表转换回元组以获取一个打乱的元组作为输出。

Python3

# Python3 code to demonstrate  
# shuffle a tuple  
# using random.sample() 
import random 
  
# initializing tuple
tup = (1,2,3,4,5)
  
# Printing original tuple
print("The original tuple is : " + str(tup))
  
# Using random.sample(), passing the tuple and 
# the length of the datastructure as arguments
# and converting it back to tuple.
tup = tuple(random.sample(t, len(t)))
  
# Printing shuffled tuple
print ("The shuffled tuple is : " + str(tup))

输出:

The original tuple is: (1, 2, 3, 4, 5)
The shuffled tuple is: (1, 5, 3, 2, 4)