簡體   English   中英

將字符串列表轉換為整數列表?

[英]Convert list of strings to list of integers?

我有一個要轉換為簡單整數數組的字符串列表。

例:

my_list = ['This is a string', 'This is a string', 'Hi! I am a string', 'I dislike strings', 'This is a string', 'Not a number']

轉換成:

[0, 0, 1, 2, 0, 3]

my_list中具有相同值的元素在轉換后的數組中都將以相同的整數結尾。

其背后的想法是,我想利用以下語法(來自matplotlib)制作散點圖,並且當y_traini是字符串時,它似乎並不喜歡它:

X_train_small_pca[y_train == i, 0]

如上所述,如何將列表轉換為整數?

應該這樣做:

>>> my_list = ['This is a string', 'This is a string', 'Hi! I am a string', 'I 
>>> dislike strings', 'This is a string', 'Not a number']
>>> mappedDict = dict(zip(set(my_list), xrange(len(my_list))))
>>> output = map(lambda x: mappedDict[x], my_list)
>>> output
[0, 0, 1, 2, 0, 3]

說明:首先刪除列表中的重復項,然后將具有單個ID(在這種情況下為int )的重復項映射到dict中。 之后,只需將列表中的每個值轉換為映射的ID即可。

您的問題:將字符串列表轉換為整數列表,其中相同的字符串應變為相同的整數(無論這些整數是什么)

列表的方法index("value")返回找到“ value”的第一個索引。 對於列表中所有相同的字符串“值”,此方法將返回相同的整數。

>>> my_list = ['This is a string', 'This is a string', 'Hi! I am a string', 'I dislike strings', 'This is a string', 'Not a number']

>>> my_list.index('This is a string')
0

>>> indexes=[my_list.index(l) for l in my_list]
>>> print(indexes)
[0, 0, 2, 3, 0, 5]
my_list = ['This is a string', 'This is a string', 'Hi! I am a string', 'I dislike strings', 'This is a string', 'Not a number']

converter = {}
i = 1

for item in my_list:
    if item not in converter:
        converter[item] = i
        i += 1

int_list = [converter[i] for i in my_list]

您想通過將函數應用於另一個列表的所有成員來創建一個列表。 這是一個列表理解。

l1 = ['1', '2', '3', '4', '5', '6']
l2 = [int(x) for x in l1]
print l2

[1、2、3、4、5、6]

當然,您會想到一些完全不同的功能,並且我不知道如何從這些字符串中獲得這些數字,但是我認為這是無關緊要的。 列表理解將使用您想要的任何功能。

l1 = ['string', 'this', 'is']
def f(s):
    return len(s)
l2 = [f(x) for x in l1]
print l2

[6,4,2]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM