将带有元组数组的 CSV 转换回 int

Convert CSV with array of tuples back to int

我有一个元组数组,逐行存储在 csv 中,我想将它们转换回来,但每次我将它们转换回来时,它们仍然是字符串,我需要它们是整数。

"(1013, 294)","(872, 258)","(744, 190)","(704, 124)","(758, 78)","(853, 121)","(862, 68)","(861, 130)","(861, 166)","(972, 123)","(979, 67)","(956, 145)","(949, 177)","(1088, 136)","(1096, 85)","(1061, 155)","(1050, 188)","(1201, 158)","(1198, 121)","(1152, 168)","(1132, 194)"
"(1037, 305)","(906, 259)","(798, 192)","(756, 126)","(790, 78)","(894, 109)","(882, 29)","(873, -14)","(875, -52)","(1010, 119)","(1046, 72)","(1012, 150)","(990, 192)","(1122, 139)","(1156, 101)","(1101, 174)","(1069, 209)","(1224, 172)","(1248, 140)","(1189, 187)","(1152, 214)"
"(1031, 315)","(891, 269)","(812, 196)","(863, 130)","(968, 101)","(865, 117)","(813, 39)","(791, -10)","(778, -54)","(985, 113)","(989, 17)","(997, -33)","(1004, -70)","(1102, 132)","(1135, 57)","(1093, 105)","(1056, 152)","(1208, 170)","(1219, 124)","(1163, 156)","(1117, 192)"

所需的输出应如下所示:

handData =[(1013, 294), (872, 258), (744, 190), (704, 124), (758, 78), (853, 121), (862, 68), (861, 130), (861, 166), (972, 123), (979, 67), (956, 145), (949, 177), (1088, 136), (1096, 85), (1061, 155), (1050, 188), (1201, 158), (1198, 121), (1152, 168), (1132, 194)]

当前代码:

with open('gesture_data.csv', 'r', newline='') as f:
            reader = csv.reader(f)
            examples = list(reader)  

给出这个:

[['(1013, 294)', '(872, 258)', '(744, 190)', '(704, 124)', '(758, 78)', '(853, 121)', '(862, 68)', '(861, 130)', '(861, 166)', '(972, 123)', '(979, 67)', '(956, 145)', '(949, 177)', '(1088, 136)', '(1096, 85)', '(1061, 155)', '(1050, 188)', '(1201, 158)', '(1198, 121)', '(1152, 168)', '(1132, 194)'], ['(1037, 305)', '(906, 259)', '(798, 192)', '(756, 126)', '(790, 78)', '(894, 109)', '(882, 29)', '(873, -14)', '(875, -52)', '(1010, 119)', '(1046, 72)', '(1012, 150)', '(990, 192)', '(1122, 139)', '(1156, 101)', '(1101, 174)', '(1069, 209)', '(1224, 172)', '(1248, 140)', '(1189, 187)', '(1152, 214)'], ['(1031, 315)', '(891, 269)', '(812, 196)', '(863, 130)', '(968, 101)', '(865, 117)', '(813, 39)', '(791, -10)', '(778, -54)', '(985, 113)', '(989, 17)', '(997, -33)', '(1004, -70)', '(1102, 132)', '(1135, 57)', '(1093, 105)', '(1056, 152)', '(1208, 170)', '(1219, 124)', '(1163, 156)', '(1117, 192)']]

您可以使用 regex 表达式将情侣中的数字和 map 匹配为整数:

import re

handData = [tuple(map(int, re.findall('\d+', string[1:-1]))) for string in examples[0]]