将字符串值列表转换为这些字符串长度的整数列表

时间:2015-12-23 08:42:29

标签: python

我虽然这很容易,基本上像

一样运行
greeter

但我似乎无法计算出范围。下面的代码带有 -

  

IndexError:列表索引超出范围

无论我如何改变范围。有什么想法吗?

table2[x][y] = len(table1[x][y])

3 个答案:

答案 0 :(得分:3)

您可以执行以下操作:(使用嵌套列表解析)

print [[len(i) for i in element] for element in table_data ]

或者,(使用地图和列表理解)

print [map(len,element) for element in table_data]

输入:

table_data = [['apples', 'oranges', 'cherries', 'banana'],
         ['Alice', 'Bob', 'Carol', 'David'],
         ['dogs', 'cats', 'moose', 'goose']]

输出:

[[6, 7, 8, 6], [5, 3, 5, 5], [4, 4, 5, 5]]

答案 1 :(得分:1)

for i in range(len(table_data)):
  for j in range(len(table_data[i])):
    table_data[i][j] = len(table_data[i][j])

你去。

答案 2 :(得分:0)

table_data = [['apples', 'oranges', 'cherries', 'banana'],
         ['Alice', 'Bob', 'Carol', 'David'],
         ['dogs', 'cats', 'moose', 'goose']]
new_table = []

def string_to_length(message):
global new_table
for x in range(len(message)):
    b = 0
    sub_table =[]  # create an empty subarray
    while b < len(message[0]):
        # python is not like C so u can not directly access index by index
        sub_table.append (len(message[x][b])) # append len value
        b = b+1
    new_table.append(sub_table) # append the subtable to new_table
#print(new_table)

string_to_length(table_data)

print new_table