python编辑一串字符串的列表 [英] pythonically editing a list of tupples of strings

查看:87
本文介绍了python编辑一串字符串的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

mysql已输出格式如下的元组列表

mysql has output a list of tuples of the form

a=[("1","2","3"),("4","5","6"),("7","8","9")]

我想要一个形式为元组的列表

I want a list of tuples of the form

c=[("2","3"),("5","6"),("8","9")]

即每个元组的最后两个元素,因此我可以将其放入我的sql executemany命令中并获取下一个数据.

i.e. the last two elements of each tuple, so i can put that into a my sql executemany command and get the next piece of data.

我的直觉是我可以通过命令获得所需的矩阵

my intuition was that i could get the desired matrix with the command

c=[for b in a: b[1:]]

但是python,不喜欢那样.为什么这样不起作用,以及获取所需元组列表的最Python方式是什么?

but python, doesn't like that. Why doesn't that work, and what's the most pythonic way of getting the desired list of tuples?

推荐答案

自此,您要使用切片 [1:] (例如其他答案)在每个元组中的元素数不为3时将不起作用.

Since, you want the last two elements of each tuple, using the slice [1:] (like in the other answers) won't work when the number of elements in each tuple is not 3.

相反,请对 [:-2] :

a = [("1","2","3"),("4","5","6"),("7","8","9")]
a = [t[-2:] for t in a]
print(a)

输出:

[('2', '3'), ('5', '6'), ('8', '9')]

这篇关于python编辑一串字符串的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆