【问题标题】:python: shuffle list in respect to other attributepython:关于其他属性的洗牌列表
【发布时间】:2014-12-09 12:32:56
【问题描述】:

我有两个列表,我想根据另一个列表中的属性对其中的值进行洗牌。例如:

list1 = np.array([1,1,1, 2,2,2, 3,3,3])  # spaces for better understanding
list2 = np.array([1,2,3, 4,5,6, 7,8,9])
result = [4,5,6, 1,2,3, 7,8,9]

我解决了这个问题

y = split(list2, len(np.unique(list1)))
np.random.shuffle(y)
result = np.array(y).flatten()

我希望它也适用于 list1 中的属性不在一起的情况。示例:

list1 = np.array([1,2,3,1,2,3,1,2,3])
list2 = np.array([1,2,3,4,5,6,7,8,9])
result = [2,1,3,5,4,6,8,7,9]

【问题讨论】:

    标签: python random shuffle


    【解决方案1】:

    解决了:

    uniques = np.unique(list1)
    shuffled = uniques.copy()
    np.random.shuffle(shuffled)
    
    result = list2.copy()
    for orig, new in zip(uniques, shuffled):
        result[np.where(list1==orig)] = list2[np.where(list1==new)]
    

    【讨论】:

      猜你喜欢
      • 2018-01-30
      • 1970-01-01
      • 2012-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-16
      • 2013-03-20
      • 1970-01-01
      相关资源
      最近更新 更多