我正在尝试删除列表中相同元组内存在的重复元素
list_1= [('nissan', 'nissan'), ('buy', 'toyota'), ('sale', 'toyota'), ('cheap', 'toyota')]
我想要的输出是:
list_1= [('buy', 'toyota'), ('sale', 'toyota'), ('cheap', 'toyota')]
我尝试使用“ set”,但是它只会删除重复的元组!
答案 0 :(得分:3)
您可以使用列表理解,这意味着通过迭代现有列表来生成新列表(可能按条件过滤):
TimeZone.getTimeZone("GMT+03")
答案 1 :(得分:0)
请参见
<template>
<div class="connections">
<canvas id="pixi"></canvas>
</div>
</template>
<script>
import * as PIXI from 'pixi.js'
export default {
name: 'ConnectionsLayer',
methods: {
drawPixi() {
var canvas = document.getElementById('pixi')
const app = new PIXI.Application({
width: window.innerWidth,
height: window.innerHeight,
antialias: true,
transparent: true,
view: canvas,
})
let graphics = new PIXI.Graphics()
graphics.lineStyle(8, 0x000000)
//start
graphics.moveTo(300, 250)
//end
graphics.lineTo(500, 250)
app.stage.addChild(graphics)
},
},
mounted() {
this.drawPixi()
},
}
``
输出
lst = [('nissan', 'nissan'), ('buy', 'toyota'), ('sale', 'toyota'), ('cheap', 'toyota')]
no_dups = [x for x in lst if x[0] != x[1]]
print(no_dups)
答案 2 :(得分:0)
使用set
list_1= [('nissan', 'nissan'), ('buy', 'toyota'), ('sale', 'toyota'), ('cheap', 'toyota')]
res=[]
for i in list_1:
if len(set(i)) == 2:
res.append(i)
print(res)
答案 3 :(得分:0)
使用filter
:
list_1= [('nissan', 'nissan'), ('buy', 'toyota'), ('sale', 'toyota'), ('cheap', 'toyota')]
list_no_duplicates = list(filter(lambda x: x[0] != x[1], list_1))
print(list_no_duplicates)
# [('buy', 'toyota'), ('sale', 'toyota'), ('cheap', 'toyota')]
答案 4 :(得分:0)
您提到的输出与问题中的输出不同
但是如果您想删除列表中同一元组内存在的重复元素,可以通过
list_1 = [x for x in [tuple(set(item)) for item in list_1]]
给出输出
[('nissan',), ('buy', 'toyota'), ('toyota', 'sale'), ('cheap', 'toyota')]