简体   繁体   English

打印值不带双方括号python

[英]Print value without double square brackets python

I'm trying to print a value without the double square brackets in python. 我正在尝试在python中打印不带双方括号的值。 Say I have 说我有

a = [[2]]

and I want to print the value into a textfile or whatnot. 我想将值打印到文本文件或其他。 With

print(a)

I of course get 我当然会

[[2]]

I tried 我试过了

 print(np.asarray(a))
 print(str(a))
 print("" . join(str(a)))

all these commands return the same as above. 所有这些命令都返回与上面相同的命令。 How can I print the value without brackets? 如何打印不带括号的值?

using a[0][0], for example if a = [1,[2,3]] 使用a [0] [0],例如,如果a = [1,[2,3]]

a[1][1]

this gives you 3 这给你3

[[2]] is a list containing a list containing the number 2. [[2]]是一个包含数字2的列表的列表。

To get the first element from a list, use a[0] . 要从列表中获取第一个元素,请使用a[0]

To get the first element from a list and then the first element of that, use a[0][0] . 要从列表中获取第一个元素,然后从列表中获取第一个元素,请使用a[0][0]

Although the answer is given in the comments below your question, this will just give you some idea on indexing. 尽管答案在问题下方的注释中给出,但这只会给您一些有关索引的想法。 What you have is an integer value as a sublist within the list. 您拥有的是一个整数值作为列表中的子列表。

a = [[2]]

If you print its length and type 如果打印其长度和类型

print (len(a), type(a))

you get 你得到

1 <class 'list'>

which means your a is a list with length 1. Since in python, indexing starts from 0 , the content of list a is accessed as a[0] . 这意味着您的a是一个长度为1的列表。由于在python中,索引从0开始,因此列表a的内容以a[0] a形式访问。 But now repeating the above step again, 但是,现在再次重复以上步骤,

print (len(a[0]), type(a[0]))

yields 产量

1 <class 'list'>

which means the sublist a[0] is itself a list of length 1 and the content of this sublist a[0] can be accessed using the index 0 . 这意味着子列表a[0]本身就是一个长度为1的list ,并且可以使用索引0访问此子列表a[0]的内容。 This means 0 index of a[0] as a[0][0] . 这意味着a[0] 0索引为a[0][0] This can go on forever depending on the number of sublists. 这可能会一直持续下去,具体取决于子列表的数量。 But eventually the integer inside will result in TypeError because integer has no length. 但是最终内部的整数将导致TypeError因为整数没有长度。

print (len(a[0][0]))

yields 产量

TypeError: object of type 'int' has no len()

Hope you understood the gist behind all this sublist and indexing. 希望您了解所有此子列表和索引的要点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM