python提取元素从列表中带有偶尔模式成元组的元素
我的列表具有类似的模式[float,string,float string ...],但偶尔在模式中会更改为[float,string,float,string,string,string,float string ...]。我要做的是将列表的元素提取到以(float,name,nontype或str)格式的元组中提取元组,以便以后使用它。这是一个很小的例子:
arr = [1150.1, 'James', 3323.1, 'Steve', 9323.1, 'John', 1233.1, 'Gary', 'criminal', 3293.1, 'Josh', 9232.1, 'Daniel', 'criminal']
我想提取列表,因此元组看起来像:
(1150.1,james,none)
(3323.1,steve,none)
(9323.1,John,None)
(1233.1,Gary,犯罪)
(3293.1,JOSH,NONE)
(9232.1,Daniel,Crorial)< /code>
到目前为止,我尝试检查该类型数组中的下一个索引,但它无法正常工作:
for index in range(len(arr)):
if type(arr[index]) == float and type(arr[index+1]) == str:
tup = arr[index], arr[index+1], None
print(tup)
elif type(arr[index]) == float and type(arr[index+1]) == str and type(arr[index+2]) == str:
tup = arr[index], arr[index + 1], arr[index+2]
print(tup)
I have a list that is has a pattern like this [float, string, float string...] but occasionally in the pattern it changes to [float, string, float, string, string, float string...]. What I want to do is to extract the elements of the list to a tuple in the format of (float, name, NoneType or str) to do something with it later. Here is a small example:
arr = [1150.1, 'James', 3323.1, 'Steve', 9323.1, 'John', 1233.1, 'Gary', 'criminal', 3293.1, 'Josh', 9232.1, 'Daniel', 'criminal']
I want to extract the list so the tuples look like this:
(1150.1, James, NONE)
(3323.1, Steve, NONE)
(9323.1, John, NONE)
(1233.1, Gary, criminal)
(3293.1, Josh, NONE)
(9232.1, Daniel, criminal)
so far i've tried checking for the next index in the array for the type but it's not working:
for index in range(len(arr)):
if type(arr[index]) == float and type(arr[index+1]) == str:
tup = arr[index], arr[index+1], None
print(tup)
elif type(arr[index]) == float and type(arr[index+1]) == str and type(arr[index+2]) == str:
tup = arr[index], arr[index + 1], arr[index+2]
print(tup)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用辅助列表跟踪自上次浮动值以来所看到的数组元素。每当您看到浮子时,都会将现有元素变成元组并清除辅助列表:
此输出:
You can keep track of the array elements you've seen since the last floating value using an auxiliary list. Whenever you see a float, turn the existing elements into a tuple and clear the auxiliary list:
This outputs:
您可以检查“ float”,“字符串”模式并相应地附加:
You could check for the "float", "string" pattern and append accordingly:
另一个解决方案:
打印:
Another solution:
Prints: