如果我有以下元组:
("200", "Harry", "50000", "Dog", "jumbo"),("200", "Harry", "50000", "Dog", "jumbo"), ("200", "Harry", "50000", "Dog", "jumbo")
我希望将所有字符串数转换为整数,以便我可以正确格式化整数并进行计算,以便我可以相互比较元组列表,例如打印名称为#34; harry"的元组。我该怎么做呢?我的变量包含几个元组,所有元组都有不同的信息,所以我使用for循环迭代并单独打印出来,但这就是我所知道的。
答案 0 :(得分:3)
>>> a_tuple = ("200", "Harry", "50000", "Dog", "jumbo")
>>> tuple((int(x) if x.isdigit() else x) for x in a_tuple)
(200, 'Harry', 50000, 'Dog', 'jumbo')
>>> all_tuples = (
... ("200", "Marry", "50000", "Dog", "jumbo"),
... ("200", "Harry", "50000", "Dog", "jumbo"),
... ("200", "Happy", "50000", "Dog", "jumbo"),
... )
如果名称的位置是固定的(第二项):
>>> [t for t in all_tuples if t[1] == 'Harry']
[('200', 'Harry', '50000', 'Dog', 'jumbo')]
如果位置不固定:
>>> [t for t in all_tuples if 'Harry' in t]
[('200', 'Harry', '50000', 'Dog', 'jumbo')]
答案 1 :(得分:3)
我会使用像
这样的东西def safe_int(v):
try:
return int(v)
except ValueError:
return v
这样:
>>> tup = ("200", "Harry", "50000", "Dog", "jumbo")
>>> tuple(map(safe_int, tup))
(200, 'Harry', 50000, 'Dog', 'jumbo')
答案 2 :(得分:0)
你可以这样做:
result = []
data = [("200", "Harry", "50000", "Dog", "jumbo"),("200", "Harry", "50000", "Dog", "jumbo"), ("200", "Harry", "50000", "Dog", "jumbo")]
for item in data:
result.append((int(item[0]), item[1], int(item[2]), item[3], item[4]))
甚至:
result = [((int(item[0]), item[1], int(item[2]), item[3], item[4])) for item in data]
这会使用整数而不是字符串创建新元组(因为元组是不可变的)。
要查找"Harry"
的所有元组,您可以检查item[1] == "Harry"
。