在 python 中剪切以逗号分隔的字符串

Cut strings separated by comma in python

我想读取我的 sql 数据库值并将它们分配给我将用于进一步处理的变量。

import mysql.connector
mydb = mysql.connector.connect(
  host='x.x.x.x',
  user="admin",
  password="secret",
  database="dbname"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM dbname.bb_users")
myresult = mycursor.fetchall()
for x in myresult:
  print(x)

从我的数据库返回以下值:

(78, 0, 2, b'', 0, '63.15.172.56', 1646404832, 'mozz@abc.com', Itally, 1646404832, 1646404873, 1646404832, 0, 'viewmc.php')
(79, 0, 2, b'', 0, '10.76.234.152', 1646988672, 'fenster@yahoo.com', India, 1646988672, 1646989676, 1646988672, 1646988813, 'viewtp.php')
(80, 0, 2, b'', 0, '63.14.61.115', 1648820721, 'frans@hotmail.com', France, 1648820721, 1648820721, 1648820721, 0, 'viewrc.php')
(81, 0, 2, b'', 0, '63.15.190.171', 1648820770, 'mozzillo@gmail.com', London, 1648820770, 1648821169, 1648820770, 0, 'view.php')
(82, 0, 2, b'', 0, '63.15.189.113', 1648821062, 'fiewood@yahoo.com', America, 1648821062, 1648821598, 1648821062, 1648821181, 'purge.php')
(83, 0, 2, b'', 0, '63.13.134.216', 1649430673, 'joseph@outlook.com', China, 1649430673, 1649701711, 1649430673, 1649701685, 'view.php') 

我想读取每第 6 个(IP 地址)、第 8 个(电子邮件)和第 9 个(国家/地区)值,以逗号分隔并分配给以下变量

IP 地址 = 第 6 个值,电子邮件 = 第 8 个值,位置 = 第 9 个值

(78, 0, 2, b'', 0, '63.15.172.56', 1646404832, 'mozz@abc.com', Itally, 1646404832, 1646404873, 1646404832, 0, 'viewmc.php')

您确定您的数据库给您 Itally 打字错误而不是 '' 之间吗?


您可以通过以下方式访问您的 tuple

for my_tuple in myresult:
   ip = my_tuple[7]
   email = my_tuple[9]
   location = my_tuple[10]

也许将数据保存到 list of dictionaries?

res: list[dict[str, int | str]] = []
for my_tuple in myresult:
    res.append({
        'ip' = my_tuple[7],
        'email' = my_tuple[9],
        'location' = my_tuple[10]
    })

然后您将能够像这样访问res

>>> # Lets say you want the ip of the 4th user...
>>> res[3]['ip']
1648820770

请注意,myresult 包含一个元组列表。您可以像这样访问多维数组:(一个例子)

首先指定要访问的元组:

tuple_of_interest = myresult[n]    #n is the indexnumber of the element

那么您想要访问元组中的元素:

ip = tuple_of_interest[5]
e_mail = tuple_of_interest[7]
country = tuple_of_interest[8]

记住索引从 0 开始...