如何打印二元组构成的元组中各子元组首元素的唯一值
嘿,我来帮你捋捋这个问题~你当前的代码存在一个逻辑漏洞:你写的判断条件row[0] not in rows是行不通的——rows里的每一项都是二元组(比如('python', 'kivy')),而row[0]是字符串类型(比如'python'),字符串永远不会出现在由二元组组成的rows里,所以这个条件始终为真,导致同一个元素会被重复打印好几次。
要实现只输出每个子元组第一个位置的唯一元素,这里有几种简单靠谱的解法:
方法一:用集合记录已出现的元素(保留原始出现顺序,Python 3.7+适用)
这种方法会在遍历过程中记录已经打印过的元素,避免重复输出:
rows = (('python', 'kivy'), ('python', 'tkinter'),("python","wxpython"), ('PHP', 'bootstrap'),('html', 'ajax'),('html', 'css')) seen = set() for row in rows: first_item = row[0] if first_item not in seen: seen.add(first_item) print(first_item)
方法二:提取所有首元素后去重
如果不需要严格保留元素的原始出现顺序,这种写法更简洁:
rows = (('python', 'kivy'), ('python', 'tkinter'),("python","wxpython"), ('PHP', 'bootstrap'),('html', 'ajax'),('html', 'css')) unique_first_items = {row[0] for row in rows} for item in unique_first_items: print(item)
要是需要保留原始顺序,也可以借助字典的键唯一性来实现(Python 3.7+字典会保留插入顺序):
rows = (('python', 'kivy'), ('python', 'tkinter'),("python","wxpython"), ('PHP', 'bootstrap'),('html', 'ajax'),('html', 'css')) unique_first_items = list(dict.fromkeys(row[0] for row in rows)) for item in unique_first_items: print(item)
以上几种方法都能输出你预期的结果:python、PHP、html。
内容的提问来源于stack exchange,提问作者AD WAN
相关产品推荐
相关产品推荐

