是Python中的元组,如何初始化?

时间:2019-07-18 19:54:38

标签: python python-3.x

我已经在Python中遇到了这个符号:

import kivy
import gi
kivy.require('1.11.1')
gi.require_version('Gst', '1.0')

from collections import namedtuple
from PIL import Image as Img
from kivy.app import App
from gi.repository import Gst
import pyzbar.pyzbar
from kivy.uix.image import Image
from kivy.core.camera import Camera as CoreCamera
from kivy.properties import NumericProperty, ListProperty, \
    BooleanProperty, ObjectProperty
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
from kivy.core.window import Window
from kivy.uix.modalview import ModalView
from kivy.clock import Clock
from io import BytesIO

Builder.load_string('''
#: import Window kivy.core.window.Window
<ScanCamera>:

<CaptureBox>:
    auto_dismiss: True
    size_hint: [0.9, 0.9]
    pos_hint: {'top':0.98}
    background_normal: ''
    background_color: (1, 1, 1, 0)
    background: 'white.png'
    BoxLayout:
        orientation: 'vertical'
        size_hint: [1,1]
        BoxLayout:
            orientation: 'horizontal'
            size_hint_y: 0.08
            Label:
                id: barc
                text: 'Geen strepieskode'
                size_hint_x: 0.7
                color: (0,0,0,1)
            Button:
                text: 'Kanselleer'
                background_normal: ''
                color: (0,0,1,1)
                size_hint_x: 0.3
                on_release: app.root.un_open()
<BarcWin>:
    ActionBar:
        pos_hint: {'top': 1, 'right': 1}
        color: (1,1,1,1)
        canvas.before:
            Color:
                rgba: (0,0,0,1)
            Rectangle:
                pos: self.pos
                size: self.size
        ActionView:
            use_separator: True
            ActionPrevious:
                title: ''
                with_previous: False
                app_icon: ''
            ActionButton:                
                color: (0,0,0,1)
                background_normal: ''
                Image:
                    source: 'gear_2.png'
                    center_y: self.parent.center_y
                    center_x: self.parent.center_x
                    size: self.parent.width /1.7, self.parent.height/ 1.7
                    allow_stretch: True
            ActionButton:
                color: (0,0,0,1)
                size_hint_x: 0.09
                background_normal: ''
                Image:
                    source: 'dustbin_backgrnd_792521.png'
                    center_y: self.parent.center_y
                    center_x: self.parent.center_x
                    size: self.parent.width /1.7, self.parent.height/ 1.7
                    allow_stretch: True
    ScanCamera:
        pos_hint: {'top': 0.9, 'right': 1}
        size_hint: [1, 0.8]
        canvas.before:
            PushMatrix
            Rotate:
                angle: 0
                origin: self.center
        canvas.after:
            PopMatrix
            Line:
                width: 2.
                rectangle: (self.x + 40, self.y + 40, self.width/1.1, self.height/1.12)
    ToggleButton:
        id: show_bcode
        pos_hint: {'bottom': 1, 'right': 1}
        size_hint: [1, 0.1]
        color: (1,1,1,1)
        background_color: (0,0,0,0)
        background_normal: ''
        canvas.before:
            Color:
                rgba: (.18,.36,.61,1) if self.state=='down' else (0,0,0,1) 
            Rectangle:
                pos: self.pos
                size: self.size
        text: 'Hier kom die barcode...'


''')
class CaptureBox(ModalView):
    pass
class BarcWin(FloatLayout):
    choice = ObjectProperty(CaptureBox())
    cam_cam = ObjectProperty(None)
    def __init__(self, **kwargs):
        super(BarcWin, self).__init__(**kwargs)
        self.cam_cam = ScanCamera()
    def open_choice(self):
        self.choice.open()
    def un_open(self):
        self.choice.ids.barc.text = 'Geen strepieskode'
        ScanCamera.got_bcode = False #make boolean property false after clicking exit
        self.cam_cam.start_cam() #call start camera function in ScanCamera class
        self.choice.dismiss()
class ScanCamera(Image):
    play = BooleanProperty(True)
    index = NumericProperty(-1)
    resolution = ListProperty([Window.width, Window.height])
    symbols = ListProperty([])
    code_types = ListProperty(set(pyzbar.pyzbar.ZBarSymbol))
    Symb = namedtuple('Symb', ['type','data'])
    app_ini_ = ObjectProperty(None)
    got_bcode = BooleanProperty(False)
    def __init__(self, **kwargs):
        self._camera = None
        super(ScanCamera, self).__init__(**kwargs)
        if self.index == -1:
            self.index = 0
        on_index = self._on_index
        fbind = self.fbind
        fbind('index', on_index)
        fbind('resolution', on_index)
        on_index()
        self.app_ini_ = App.get_running_app()

    def on_tex(self, *l):
        self.canvas.ask_update()
        if not self.texture == None and not self.got_bcode:
            self.symbols = self._detect_qrcode_frame(texture=self.texture, code_types=self.code_types)
            if not self.symbols == []:
                for s in self.symbols:
                    if s.data:
                        if s.data.decode('utf-8') != "":
                            self.app_ini_.root.ids.show_bcode.text = s.data.decode('utf-8')
                            self.app_ini_.root.choice.ids.barc.text = s.data.decode('utf-8')
                            self.app_ini_.root.open_choice()

    def _on_index(self, *largs):
        self._camera = None
        if self.index < 0:
            return
        if self.resolution[0] < 0 or self.resolution[1] < 0:
            return

        self._camera = CoreCamera(index=self.index,
                                  resolution=self.resolution, stopped=True)


        self._camera.bind(on_load=self._camera_loaded)
        if self.play:
            self._camera.start()
            self._camera.bind(on_texture=self.on_tex)
    def _camera_loaded(self, *largs):
        self.texture = self._camera.texture
    def on_play(self, instance, value):
        if not self._camera:
            return
        if value:
            self._camera.start()
        else:
            self._camera.stop()
    def _detect_qrcode_frame(self, texture, code_types):
        if not self.got_bcode:
            image_data = texture.pixels
            size = texture.size

            pil_image = Img.frombytes(mode='RGBA', size=size,
                                            data=image_data)
            bcode = []
            codes = pyzbar.pyzbar.decode(pil_image, symbols=code_types)
            if codes != []:
                self.got_bcode = True #this boolean property becomes true when code is read
                self._camera.stop() #this stops the camera once bcode is read
                for code in codes:
                    symbol = self.Symb(type=code.type, data=code.data)
                    bcode.append(symbol)
                return bcode
            else:
                self.got_bcode = False
                return []
    def reset_cam(self):
        self.reset()
    def start_cam(self, *largs):
        self._camera = None
        self.play = True
        print(self.texture, 'Begin start', self._camera, largs, self.index, self.resolution)
        self._camera = CoreCamera(index=self.index,
                                  resolution=self.resolution, stopped=True) #re initialize the camera
        self.texture = self._camera.texture #re-initialize the uix.image widget with core.camera texture
        if self.play:
            self._camera.start() #start core.camera
            self._camera.bind(on_texture=self.on_tex)
        print(self.texture, 'End start', self._camera)
class TestCamera(App):
    title = 'Scan Camera'
    def build(self):
        return BarcWin()
    def on_stop(self):
        cc = ScanCamera()
        print('Stop')
        cc._camera.stop()
    def on_pause(self):
        return True
    def on_resume(self):
        pass

TestCamera().run()

是元组吗?默认情况下如何初始化val?

如何在此结构中插入新元素?

我尝试添加一个新元素,例如:

val = [
  ('Peter', 'Lowstreet 4'),
  ('Amy', 'Apple st 652')
]

for i in range(sheet.nrows): code = sheet.cell_value(i, 0) name = sheet.cell_value(i, 1) rows.append((name, code)) 在列表中

4 个答案:

答案 0 :(得分:2)

尽管我确定val是一个列表,而val[0]val[1]是元组,但让我们检查一下Python3 REPL的内容。

Python 3.6.8 (default, Jan 14 2019, 11:02:34) 
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> val = [
...   ('Peter', 'Lowstreet 4'),
...   ('Amy', 'Apple st 652')
... ]
>>> type(val)
<class 'list'>
>>> isinstance(val, list)
True
>>> isinstance(val[0], tuple)
True

现在让我们向刚初始化的元组列表中添加一个新元素。

>>> val.append(('Foo', 'bar'))
>>> val
[('Peter', 'Lowstreet 4'), ('Amy', 'Apple st 652'), ('Foo', 'bar')]

请注意,在Python中,列表不需要是同质的。因此,如果您来自非动态语言背景,那么以下内容是完全有效的,但令人困惑。

>>> val.append('Dog')
>>> val
[('Peter', 'Lowstreet 4'), ('Amy', 'Apple st 652'), ('Foo', 'bar'), 'Dog']

答案 1 :(得分:1)

这似乎是一个元组列表。您应该查看lists的文档,但为简单起见,我建议使用append。只需将您使用的列表插入方法与正确的参数一起应用即可(其中一个应为元组,但由于诸如clone之类的方法,您可能能够创建另一个元组列表)。如果您明确知道要在列表中插入元素的索引,则可以使用insert方法。

答案 2 :(得分:1)

这是一个包含多个元组的列表:

type(val)
#list

如何添加新元素(元组,数字,字符串,为它命名)?

val.append(('serafeim','apple master'))
val.append('hello john')

[('Peter', 'Lowstreet 4'),
 ('Amy', 'Apple st 652'),
 ('serafeim', 'apple master'),
  'hello john']

如何更改元素?

val[0] = ('new','new')

val
[('new', 'new'),
 ('Amy', 'Apple st 652'),
 ('serafeim', 'apple master'),
  'hello john']

再次替换/更改

val[0] = 'overwrite'

val
['overwrite',
 ('Amy', 'Apple st 652'),
 ('serafeim', 'apple master'),
  'hello john']

答案 3 :(得分:0)

In [81]: val = [ 
    ...:   ('Peter', 'Lowstreet 4'), 
    ...:   ('Amy', 'Apple st 652') 
    ...: ]                                                                                                                                                                                                                                                                                                                    

In [82]: type(val)                                                                                                                                                                                                                                                                                                            
Out[82]: list

In [83]: isinstance(val, list)                                                                                                                                                                                                                                                                                                
Out[83]: True

In [84]: t = val[0]                                                                                                                                                                                                                                                                                                           

In [85]: t                                                                                                                                                                                                                                                                                                                    
Out[85]: ('Peter', 'Lowstreet 4')

In [86]: type(t)                                                                                                                                                                                                                                                                                                              
Out[86]: tuple

In [87]: isinstance(t, tuple)                                                                                                                                                                                                                                                                                                 
Out[87]: True

In [88]: isinstance(val[0], tuple)                                                                                                                                                                                                                                                                                            
Out[88]: True

In [89]: pwd                                                                                                                                                                                                                                                                                                                  
UsageError: CWD no longer exists - please use %cd to change directory.

In [90]: cd                                                                                                                                                                                                                                                                                                                   
/Users/apanchapakesan

In [91]: isinstance(val[1], tuple)                                                                                                                                                                                                                                                                                            
Out[91]: True